简体   繁体   中英

How to set a UITextView in a UIScrollView with AutoLayout

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:

在此处输入图片说明

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

If I am understanding you correctly, it sounds like you are having issues with setting your scrollView's contents so that it will scroll when it is supposed, and not scroll when it shouldn't. Correct? Then (assuming your constraints are set properly) your scrollView's contentSize should be set by autoLayout based on the size of your Content View.

Try setting a property up to dynamically control the height of the Content View. In your ViewController, create your property:

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

Then, wherever you are setting the text of your labels, you should calculate the new heights, and update your constraint based on that. For reference, here is a question regarding how to determine the height of text in a label.

Once you have the height you can set it like this:

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

I hope that helps. In my own experience, I have been limiting my use of UIScrollView since the way it has been updated to use AutoLayout. I mostly use UITableView & UICollectionView in its place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM