user3252154 user3252154 - 18 days ago 6
iOS Question

UIButton at bottom of UIScrollView not working

My UI structure goes like this:

- View
- Scroll View
- Container View
- Dynamically added UI element
- Dynamically added UI element
- Dynamically added UI element
- ....
- UIButton


After adding all the UI elements (including the UIButton with an UITapGestureRecognizer) and updating the UIScrollView size with following method...

func updateScrollViewSize() {
var contentRect = CGRect.zero
for view in containerView.subviews {
contentRect = contentRect.union(view.frame)
}
contentRect.size = CGSize(width: scrollView.contentSize.width, height: contentRect.height + TRAILING_SCROLLVIEW_SPACE)
scrollView.contentSize = contentRect.size
}


...I noticed that it will only work if I add a UIButton at the top of the view - the ones I only reach by scrolling (e.g. the one at the bottom) do not.

Well, I thought, so the button gets created outside of the container views' frame, thus I added the following line to my
updateScrollViewSize
method.

containerView.frame.size = contentRect.size


Sadly, this did not solve my problem.

I tried finding a solution for quite some time now, but none could help me out. I'm still 99% sure that it has something to do with my Container Views' frame, but I simply can`t figure out how to fix this. Any help would be appreciated!

Answer

call layoutIfNeeded() on your top view after creating your subviews if using any constraints. make sure the scrollView's contentSize matches your containerView.frame (not .bounds, since this will not tell you if for instance your frame y-position is below zero.

Comments