Emma Campbell Emma Campbell - 1 year ago 89
Swift Question

Making the controller extend with the amount of text in UILabel in iOS

I'm quite new to Swift and iOS. I'm working on just getting things working so ignore the terrible UI. At the moment my text runs off the screen of the controller and I would like it make it so that depending on how long the text is the controller will allow for scrolling to accommodate it.

How can I do this with Swift and iOS?

Screenshot of problem

Answer Source

First, you should place all your subviews (UILabel, UIImage etc.) in a UIScrollView.

Then, you have two options:

  • Going springs and struts: Once the frames of all subviews are set you can update the scroll view's contentSize property so it allows you to scroll. You can do this preferably in viewDidAppear method as all the frames get their exact value in there:

    override func viewDidAppear(_ animated: Bool) {
      scrollView.contentSize = CGSize(width: view.frame.width, height: bottomLabel.frame.maxY)
  • AutoLayout: Using Autolayout, you no longer need to set the contentSize property explicitly. Just make sure you set vertical and width constraints correctly so AutoLayout will infer the contentSize automatically. Your subviews inside scrollView should be laid out as follows:

       Scroll View
    |   Top Label  |
    | ------------ | v:10pt
    |              |
    |     Image    | image.width = view.width
    |              |
    | ------------ | v:10pt
    | Bottom Label |

You can download the test project and see the constraints I set in the Interface Builder.

Here is the result I got:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download