Dynamic UILabel content inside of a UIScrollView

2019-04-10 03:15发布

问题:

I've got a UILabel (amongst other controls) stored within a UIScrollView. I want to dynamically populate the UILabel so that it automatically expands its height to fit its contents. I'm just wondering what the best practice is with regards to resizing the UILabel while also ensuring that its parent UIScrollView will also expand its scrollable area.

I've tried to set the UILabel's # of Lines to 0, which I've read should automatically expand the UILabel to fit its contents, but I'm not having much luck. In terms of recalculating the UIScrollViews scrollable area, I imagine it's a case of calculating the height of its children after the UILabel is populated.

回答1:

After setting the new text in the UILabel, call sizeToFit on it. You can then set the UIScrollView's contentSize property to match the UILabel's new frame size (and/or adjust the positions of the other views in the UIScrollView.

You may need to store the UIScrollView's contentOffset prior to setting its contentSize and then set the contentOffset back to its saved value again.