Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set scrollview height programmatically

How can I set the scrollview height programmatically in Xcode 9 with Swift 4? I've set a constraint for the scrollview height and added that as an outlet. But when I change the outlet constant value programmatically it doesn't change the height.

Example:

@IBOutlet weak var scrollview_height: NSLayoutConstraint!

override func viewDidLoad() {
     super.viewDidLoad()
     self.scrollview_height.constant = 245
}
like image 255
Sean Gallagher Avatar asked Dec 01 '25 22:12

Sean Gallagher


2 Answers

The height of the ScrollView should be given by it's content and not for you to change manually. At best if you want to do something like that, you have a view inside the scrollView and change the size of that view instead.

Step-by-step:

  • Add a ScrollView to your view. Set it's constraints (no height or width)
  • Add a View inside the ScrollView and set it's constraints. Additionally for a vertical scroll you might want to set it's width equal to the SuperView and ensure it has a height.
  • Create an IBOutlet for the height of the view
  • update the constant value of the constraint in code
  • If it does not update as expected, run a layoutIfNeeded on your superview after updates
like image 63
Alex Ioja-Yang Avatar answered Dec 04 '25 14:12

Alex Ioja-Yang


You have to increase the content Size of your scrollView instead of increasing the frame of scrollView.

self.scrollview.contentSize = CGSize(width: screenWidth, height: yourDesiredHeight) 

the scrollable contentSize of scrollView will change According to it.

like image 26
Ajay saini Avatar answered Dec 04 '25 14:12

Ajay saini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!