I have a contentview (Defined in an xib file) which has some labels and two buttons in it (white view on screenshot 1.a). If we came how It is shown on the screen, let me draw the scheme;
ViewController View -> View (Custom View Class) -> UIScrollView -> ContentView (Xib file)
Buttons are placed related to bottom margin. They both placed to bottom. Top button has a constraint which has 10 constant related to bottom of last label (This is greater than equal constraint
and has UILayoutPriority
of 5).
Problem: When I give constraint from button to label even It is greater than equal, button stacks just 10 point below to label. Even there is so much gap in bottom. (Screenshot 2.a)
What I want to achieve: I want that If all contents are fit on the screen with minimum 10 constraint from last label to first button, don't scroll. If not, scroll.
Custom View Class:
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
func initialize() {
self.translatesAutoresizingMaskIntoConstraints = false
let name = String(describing: type(of: self))
let nib = UINib(nibName: name, bundle: .main)
nib.instantiate(withOwner: self, options: nil)
cancelButton.layer.borderColor = UIColor.darkGray.cgColor
cancelButton.layer.borderWidth = 1.0
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.scrollView)
scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
scrollView.addSubview(contentView)
self.contentView.translatesAutoresizingMaskIntoConstraints = false
//self.contentView.clipsToBounds = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
}
Example Screenshots:
If content fit into view, I want like below image. If not button can go up till It fits, If It doesn't fit even though, View should be scrollable.
Screenshot 2.a
The following line should be enough to calculate the height of the contents inside the scroll view and give you the proper behavior you expect.
contentView.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor).isActive = true