Resize UIView inside UIScrollView with AutoLayout

2019-03-18 17:04发布

I have a layout as follows(Using AutoLayout,iPad):

Xcode screenshot

The UIScrollView has Top,Bottom,Leading,Trailing space to the superview as 0. The UIView also has all four similar constraints. The second UILabel has its height set to 0 programmatically (since more than a screenful of text is shown here). Also, these four pin constraints have also been set up from the UIView to UIScrollView.

When the XIB is loaded, this UILabel shows long lines of text correctly. But scrolling does not work. This is a screenshot of the running app on an iPad:

enter image description here

The yellow background is set for the outermost view and the grey one for the UIView. If you see carefully at the end of the screenshot, the UILabel's text seems to overflow past the UIView.

I suspect that because the UIView cannot "capture" the size of it's subviews, the UIScrollView cannot calculate it's contentsize too(there's no reason for the scrollbar to work if its content view is only equal to one screen). Why is this happening even when the UILabel is clearly a subview of the UIView? If my suspicions are right, how do I set the UIView's height equal to the actual content size so that my UILabel is properly "contained" in it?

(Setting the UIView's height,width statically is not an option) .

NB: Tested the XIB without the UIView and only a single UILabel (with long text) inside a UIScrollView. Now scrolling works(since, I presume, the scroll view can calculate its content size).

NB2: I also tried the answers in this SO question and this post but my UIView simply wont extend beyond the dimensions of the screen. (I only care about horizontal scrolling)

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-18 17:44

AutoLayout issues are very hard to explain with text. I was having the same problem. I found the solution in this video. hope this will help you too.

https://www.youtube.com/watch?v=UnQsFlMGDsI

This video demonstrates how to create a UIScrollView which has some views on the top of the screen and a view on the bottom of the screen in Autolayout. UIScrollView content size is automatically adjusted to the size of the screen or to the size of the content in such way that on smaller devices scrolling is active and on larger devices scrolling is not active because it is not needed. UIButton below UITextFields always stays on the bottom of the screen and everything works on all iPhone resolutions (iPhone 4 / 5 / 6 / 6 Plus).

查看更多
登录 后发表回答