0
votes

I am trying to use a UIScrollView to show a series of UIViews. In my storyboard I have a View Controller containing a UIView that is constrained using AutoLayout.

View Controller (UIView in grey)

enter image description here

In order to call the UIScrollView I am using the following method:

func initScrollview() {

    self.mainScrollView = UIScrollView(frame: self.mainView.bounds)
    self.mainScrollView!.contentSize = CGSizeMake((self.mainView.bounds.width)*CGFloat(3), self.mainView.frame.height)
    self.mainScrollView!.backgroundColor = UIColor.greenColor() // For visualization of the UIScrollView
    self.mainScrollView!.pagingEnabled = true
    self.mainScrollView!.maximumZoomScale = 1.0
    self.mainScrollView!.minimumZoomScale = 1.0
    self.mainScrollView!.bounces = false
    self.mainScrollView!.showsHorizontalScrollIndicator = true;
    self.mainScrollView!.showsVerticalScrollIndicator = false;
    self.mainScrollView!.delegate = self

    for i in 0...3 {

        var tempView = SubView(frame: self.mainView.bounds)

        pages.insert(tempView, atIndex: i)
        self.mainScrollView!.addSubview(pages[i]);
    }

    self.mainScrollView!.scrollRectToVisible(CGRectMake(mainScrollView!.frame.size.width, 0, mainScrollView!.frame.size.width, mainScrollView!.frame.size.height), animated: false)
}

When I run my code, the UIScrollView does not fit the UIView. Instead it is too short and too wide. The result looks like this:

UIView in grey, UIScrollView in green

enter image description here

What am I doing wrong that is causing the UIScrollView to be incorrectly sized?

3
Where did you place initScrollview ? - tuledev
I have initScrollView in viewDidLoad() after super.ViewDidLoad(). I just noticed that if I print the width of mainView in viewDidLoad() I get 536.0 and if I print the width in viewDidAppear() I get 311.0. Is that expected and could it be the source of my problem? - tjlsmith
Yes. Look at my answer :) - tuledev

3 Answers

0
votes

In the above code, there no mention of adding the mainScrollView to the mainVew.

To whose view are you adding the mainScrollView? My opinion would be you are trying to add it to self.view whereas it should be to self.mainView

After the initScrollView() function is called try adding it the below code

self.mainView.addSubview(mainScrollView!)
0
votes

This would probably be easier if you had placed all these views directly in your storyboard instead of programatically. I don't see anything in your code that can't be done visually in IB. Also, if you have autoLayout active in your storyboard, setting frames and sizes in code won't work. (auto-layout will change your values on the next pass)

0
votes

You should put the codes that you init the UI element sizes base on the screen size(UIView of UIViewController) in viewDidLayoutSubviews. Because in viewDidLoad, the screen didn't adjust its size yet,