Raj Joshi
Raj Joshi

Reputation: 2669

ScrollView Add SubView in swift 3

I want to try add a view form on scroll view but view don't fully added on scroll view's frame, my code is:

import UIKit

class AddIncomeVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var views: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.contentSize = views.frame.size
        scrollView.addSubview(views)

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        views.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
    }

}

enter image description here

Thanks,

Upvotes: 7

Views: 11940

Answers (3)

Mendigo dos Bytes
Mendigo dos Bytes

Reputation: 91

The problem is: At view did load, your constraints are not updated to the new display sizes. I believe that your problem occurs because you are running the app using a simulator with different size from your storyboard... a bigger size (storyboard using iPhone SE and running at iphone 6 simulator, for example).

At View did Load, your view already exists, its true... but its constraints still have iphone SE sizes.

So, at view did load you are setting the content size (that you want with an iphone6 screen size) equal to storyboard view size (that still an iphone SE screen size).

Your solution works well. After the iOS layout all subviews, the constraints are updated to the new screen sizes, maintaining its proportions. At viewDidLayoutSubviews the "view" already have the correct constraint values... So, the view has iphone6 screen sizes, and you could set the frame with the right

Upvotes: 1

Raj Joshi
Raj Joshi

Reputation: 2669

I get solved my issue with this code:

import UIKit

class AddIncomeVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var views: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.contentSize = views.frame.size
        scrollView.addSubview(views)


    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        views.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

    }

}

Thanks all for giving valuable time for my question. enter image description here

Upvotes: 1

Sivajee Battina
Sivajee Battina

Reputation: 4174

Edit line

views.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)

to

views.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)

Upvotes: 3

Related Questions