How to set a UITextView in a UIScrollView with AutoLayout

时间:2015-06-15 17:56:10

标签: ios objective-c uiscrollview

Forgive me if this has already been answered elsewhere, but I couldn't find a thread about this:

I have a VC with the following hierarchy:

enter image description here

I want my ContentView elements to scroll within my ScrollView. I have a lot of definitions in the textView, and some are longer than others. Previously, only the longer definitions would scroll and the shorter ones wouldn't, but since I had an auto layout conflict, the links weren't able to be clicked at the end. I have the ScrollView constrained to the View and the ContentView constrained to the ScrollView. I also have the ContentView constrained equalWidth and equalHeight from the main View. In order for this solution to work, I had to set the height of the ContentView to something like 1000 pts so that longer definitions wouldn't be cut off. The only problem is that now all the definitions are scrolling (even ones that don't need to - that don't have enough text to go over the screen). And the user can scroll down and see enough white space to cover the screen, depending on how brief the definition is.

My question is: how can I arrange the constraints so that longer definitions scroll when needed and shorter ones do not - how can I set the constraint dynamically?

Thanks

1 个答案:

答案 0 :(得分:0)

如果我正确理解你,听起来你在设置你的scrollView的内容时会遇到问题,以便它在假设时滚动,而不是在它不应该滚动时滚动。正确?然后(假设您的约束设置正确),您应该根据内容视图的大小,通过autoLayout设置scrollView的contentSize。

尝试设置属性以动态控制内容视图的高度。在ViewController中,创建属性:

@property (nonatomic, strong) IBOutlet NSLayoutConstraint *contentViewHeight;

然后,无论您在何处设置标签文本,都应计算新的高度,并根据此更新约束。 For reference, here is a question regarding how to determine the height of text in a label.

一旦你有了高度,就可以这样设置:

self.contentViewHieight.constant = // Updated Height
[self.view setNeedsUpdateConstraints];

我希望有所帮助。根据我自己的经验,我一直在限制我对UIScrollView的使用,因为它已被更新为使用AutoLayout。我主要使用UITableView&取而代之的是UICollectionView。