dimanche 1 mars 2015

Adding subviews to a UIScrollview with paging in Swift

I'm creating a UIViewController containing a paged UIScrollView which should add views created from the StoryBoard.I'm referencing this article. Basically the structure is



- MyController
- UIScrollView
- subview
- subview
- ...


This is how my Storyboard looks like:



The left one is the portion of my main controller view which contains the scrollview. The right one is the "freeForm" view controller I'm using for instantiating the single pages. They both have the same size.


enter image description hereenter image description here


This is the code I'm using for the main controller:



import UIKit

class MainControllerVC: UIViewController {


@IBOutlet var tagsScrollview: UIScrollView!
var tagsPages:[UIViewController] = []
var frame: CGRect = CGRectMake(0,0,0,0)

override func viewDidLoad() {
super.viewDidLoad()

// generate tags view controller
for index in 0..<5 {

frame.origin.x = self.tagsScrollview.frame.size.width * CGFloat(index)
frame.size = self.tagsScrollview.frame.size
tagsScrollview.pagingEnabled = true
if let page:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tagsVC") as? UIViewController {

var delta = 0.2 * CGFloat(index)
page.view.frame = self.frame
page.view.backgroundColor = UIColor(red: 0.2 + delta, green: 0.2 + delta, blue: 0.2 + delta, alpha: 1.0)
self.tagsScrollview.addSubview(page.view)
tagsPages.append(page)
}

}

self.tagsScrollview.contentSize = CGSizeMake(self.tagsScrollview.frame.size.width * CGFloat(tagsPages.count), self.tagsScrollview.frame.size.height)


// Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {

super.viewWillAppear(animated)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}


I'm creating few dummy pages with different colours and a central label which has been placed in the center using auto layout.


The result is the following:


enter image description here


The first (darker) page subview gets added correctly indeed the size of the view and the position of the label is what we expect. However, the second page view is added at a wrong X position. The same is valid for the next ones. Currently I'm running the example on a iPhone 6 simulator and if I add 89 points to the self.tagsScrollview.frame.size.width when I calculate the page frame size and the scrollview contentSize the problem is solved....but only for iPhone6!!! It looks like the size of the scrollview is not what we expect as it's not enough for creating equidistant pages inside it.


I suspect an auto-layout problem,but not sure where should I start from.


This thing is driving me insane. Any help would be really appreciated.




Aucun commentaire:

Enregistrer un commentaire