UITextView

Our first project, Hello, showed that a UIView can display text. To do this, we had to subclass the UIView, override its drawRect method, and write code that called drawAtPoint(:withAttributes:).

A UITextView is a subclass of UIView that makes it easy to display one or more lines of text. All we have to do is put a string of characters into the text property of the UITextView. The string can contain the escape sequences for newline (\n), tab (\t), etc.

The text property of a UITextView is a constant string, so we cannot append to it with the compound assignment operator +=. To make the string longer, we must overwrite it with a new string.

Source code in TextView.zip

  1. AppDelegate.swift: unchanged.
  2. ViewController.swift: unchanged.
  3. View.swift: the big yellow view that occupies the screen belongs to a subclass of UITextView. We turned off its touch-sensitivity.
  4. LaunchScreen.xib.
  5. Main.storyboard.
  6. Info.plist: unchanged.

Create the project

Create a subview of class UITextView named View.

Touch-sensitivity

By turning off the editable property, we turned off the UITextView’s touch sensitivity. Had we not done that, a touch would have dispayed a blinking insertion point and a keyboard. To allow the simulator to pop up a keyboard,
Hardware → Keyboard → Toggle Software Keyboard

Special characters

“Star-cross’d” has an apostophe, not a single quote (Star-cross'd). 1–14 has an en-dash, not a dash (1-14). In Xcode,
Edit → Special Characters… → Punctuation

 star-cross’d 


 star-cross'd 


 1–14 


 1-14 

Things to try

  1. The text in the UITextView had to start with a newline (\n) because the UITextView and the status bar overlapped. Let’s move the UITextView down so it no longer overlaps. See the second screenshot above.
    1. In Info.plist, add the property “View controller-based status bar appearance” with the value NO.
    2. Add the following method to class View.
      	override func layoutSubviews() {
      		let application: UIApplication = UIApplication.sharedApplication();
      		let appDelegate: AppDelegate = application.delegate as! AppDelegate;
      		let window: UIWindow = appDelegate.window!;
      		let viewController: ViewController = window.rootViewController as! ViewController;
      		let y: CGFloat = viewController.topLayoutGuide.length;
      		let size: CGSize = window.frame.size;
      		window.frame = CGRect(x: 0, y: y, width: size.width, height: size.height);
      	}
      
    3. Now that the status bar no longer has a yellow background, its background will be black by default. We will therefore change the status bar text to white. Select the TextView project at the top of the Xcode Project Navigator. In the center panel of Xcode, select General → Deployment Info → Status Bar Style → Light.
    4. You can now remove the "\n" at the start of the text.

  2. See TextView to avoid having the table overlap with the status bar.