I’ve created a UIView, which has buttons in it. I set the constraints like this :
NSLayoutConstraint.activate([
sampleView.topAnchor.constraint(equalTo: topView.bottomAnchor, constant: 20),
sampleView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
sampleView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
])
Not added any height or bottom anchor as I want it to be dynamic in height.
Initially sampleView has no buttons, so it doesn’t appear in UI. I then add buttons in it vertical to each other and it works fine.
The problem I’m facing right now is, there is another view(tempView) just below this sampleView. And initially I set tempView’s topAnchor to sampleView’s bottomAnchor.
So it is placed properly on screen initially.
When I add buttons in sampleView, it expands, but tempView don’t. I tried with view.layoutIfNeeded() and setting the topAnchor with new height of sampleView but nothing works out for me.
Please help me with this.
2
Answers
You must do something to give
sampleView
a Height.One easy way is to add a vertical
UIStackView
as a subview ofsampleView
, constrain all 4 sides tosampleView
, and then add buttons as arranged subviews of the stack view.Quick example:
At start, because we haven’t added any buttons to the stack view, it will look like this:
Tap anywhere to add buttons — here is what we get after the first tap:
and after a couple more taps:
}