Author Topic: How can I programmatically change the size of a text view at run time?  (Read 4838 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
Even though Auto Layout allows you to dynamically resize controls at run time, there are still some finicky controls that require a little extra attention. The text view is one of these. Here is an example of how to programmatically change the height of a text view at run time:

1. Select the text view in the Storyboard design surface.

2. At the bottom-right corner of the Storyboard, click the Pin button and in the Add New Constraints popup, click the check box for Height, and then click the Add 1 Constraint button.

3. Display the Assistant Editor by clicking the button in the center of the Editor button group.

4. Make sure the correct view controller's implementation file is displayed in the Assistant Editor (the one associated with the scene you're working with).

5. Display the Document Outline panel

6. In the Document Outline panel, expand the TextView and Constraints nodes until you see the Height constraint.

7. Hold the Control key down, then click on the Height constraint and drag down into the View Controller's code file. When you see the Insert Outlet or OutletCollection popup, release the Control key and mouse button.

8. In the Create Outlet popup, enter a name for the outlet (such as textViewHeightConstraint) and then click Connect.

9. Now add code to the viewDidLoad method that changes the height of the text view. For example, the following code changes the height of the text view so it fills up the view, minus the height of the keyboard and a 10 point margin.

Code: [Select]
self.textViewHeightConstraint.constant = self.view.frame.size.height - keyBoardHeight - 10
All the best!
Kevin
Author of "Learn to Code in Swift": https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: July 18, 2015, 06:34:41 PM by kjmcneish »