Reputation: 654
I have the code:
Why UIScrollView's page width not equal to self.view width?
If I think right, self.view.frame.size.width must be equal to scroll.bounds.width and scroll.contentSize must be self.view.frame.size.width*4 (at this case), is it right?
Thx a lot!!
class ViewController: UIViewController {
@IBOutlet weak var scroll: UIScrollView!
var frame: CGRect = CGRectMake(0, 0, 0, 0)
override func viewDidLoad() {
super.viewDidLoad()
scroll.bounds = self.view.bounds
scroll.frame = self.view.frame
NSLog("%@", UIScreen.mainScreen().bounds.width);
NSLog("%@", scroll.bounds.width);
NSLog("%@", self.view.bounds.width);
NSLog("%@", scroll.contentSize.width);
let colors = [UIColor.redColor(), UIColor.greenColor(), UIColor.yellowColor(), UIColor.magentaColor()];
for index in 0..<colors.count {
frame.origin.x = self.view.frame.size.width * CGFloat(index)
frame.size = self.view.frame.size
var subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
subView.layer.borderColor = UIColor.blackColor().CGColor
subView.layer.borderWidth = 1.0;
self.scroll .addSubview(subView)
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(colors.count), self.view.frame.size.height)
}
...
}
What I see at second page:
Upvotes: 0
Views: 815
Reputation: 37290
(1) There's no need to set the bounds if you're going to set the frame one line later, so you can remove this line completely: scroll.bounds = self.view.bounds
(2) Move everything else in your viewDidLoad
to viewDidLayoutSubviews
since the frames you're setting are dependent on the view's width, which can change one the subviews have been laid out to fit the screen appropriately. But I'd also recommend only performing this code once by using a conditional since viewDidLayoutSubviews
can be called multiple times and you should only be running this code once so as not to add extra subviews unnecessarily, ex:
@IBOutlet weak var scroll: UIScrollView!
var frame: CGRect = CGRectMake(0, 0, 0, 0)
var viewLaidout:Bool = false
override func viewDidLayoutSubviews() {
if !viewLaidout {
scroll.frame = self.view.frame
let colors = [UIColor.redColor(), UIColor.greenColor(), UIColor.yellowColor(), UIColor.magentaColor()];
for index in 0..<colors.count {
frame.origin.x = self.view.frame.size.width * CGFloat(index)
frame.size = self.view.frame.size
var subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
subView.layer.borderColor = UIColor.blackColor().CGColor
subView.layer.borderWidth = 1.0;
self.scroll.addSubview(subView)
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(colors.count), self.view.frame.size.height)
viewLaidout = true
}
}
Upvotes: 1