Text view

There are three views related with text.

UILabel displays one or more lines of informational text.

UITextField allows to input a single line of text.

UITextView displays one or more lines of text. Additionally user can select, edit, and scroll text.

You can specify text color, background color and font of text.

NSAttributedString and NSMutableAttributedString classes allow you to display formatted text. You can create it directly or from html text.

Create a text views programmatically

font

UIFont class provides access to the font’s characteristics. The default font is System with size 17.

UIFontDescriptor class represents a collection of attributes that describes a font. It can be used to create or modify a UIFont object.

UIFont.TextStyle contains constants for the predefined styles:

  • body - the font for body text
  • callout - the font for callouts
  • caption1 - the font for standard captions
  • caption2 - the font for alternate captions
  • footnote - the font for footnotes
  • headline - the font for headings
  • subheadline - the font for subheadings
  • largeTitle - the font style for large titles
  • title1 - the font for first-level hierarchical headings
  • title2 - the font for second-level hierarchical headings
  • title3 - the font for third-level hierarchical headings
Example how to create a font object
let font1 =  UIFont.preferredFont(forTextStyle: .body)
let font2 = UIFont(name: "Helvetica Neue", size: 15)
let font3 = .systemFont(ofSize: 14, weight: .regular)

text editing processing

UITextViewDelegate protocol allows you to adjust the text a user is editing (such as in the case of a spell-checker program) or to modify the intended insertion point.

UITextFieldDelegate protocol allows you to response to important changes in UITextField. For example you can validate text that was typed by the user.

Protocol methods are not called when changing text programmatically. You can call them manually.

var valValue: String? = nil {      
        didSet {
            if valEdit.text != valValue {
                valEdit.text = valValue
                textViewDidChange(valEdit)
            }
        }
    }
How to limit the entered text to 10 characters
click on UITextView

attributed text

NSAttributedString object manages character strings and associated sets of attributes that apply to individual characters or ranges of characters in the string.

The default font for NSAttributedString objects is Helvetica 12-point, which may differ from the default system font for the platform.

NSMutableAttributedString is mutable version of NSAttributedString.

attributedText property of views such UILabel defines attributed text.

Example how to modify attributed string
let txt = "Hello world"
        
// default style for text
let attributes1 = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
        
// large red text
let attributes2 = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 24),
                   NSAttributedString.Key.foregroundColor: UIColor.red]
        
let attributedText = NSMutableAttributedString(string: txt, attributes: attributes1)

// change style of a part of the string ("lo wo")
attributedText.setAttributes(attributes2, range: NSRange(location: 3, length: 5))
       
label.attributedText = attributedText
How to justify text
How to compose attributed string
How to iterate over styles of characters
Attributed text from the html text

UITextView allows to detect and open links.

textView.isEditable = false
textView.dataDetectorTypes = UIDataDetectorTypes.Link
// a phone number will be displayed as a clickable phone number link.
textView.text = "my phone +7 (961) 000-00-00"

Also you can use an attributed string and a text view delegate to assign a custom click handler.

Clickable link

auto height

With auto layout, the UITextView can automatically grow when content bigger then current size.

tv.textContainer.lineBreakMode = .byWordWrapping
tv.isScrollEnabled = false // important for automatic height

When the UITextView is in a table cell, you will also want to change the cell's height. To do this, you need to detect a change in the number of lines and reload the cell.

If you want to automatically resize when the user enters text, use the UITableView update API.

// MARK: - MyCellDelegate
extension MyViewController: MyCellDelegate {
    
    func requestRefresh(indexPath: IndexPath?, newValue: String?) {
        guard let indexPath = indexPath else { return }
       
        srcItems[indexPath.row].value = newValue
        myTableView.reloadRows(at: [indexPath], with: .automatic)
        // myTableView.beginUpdates()
        // myTableView.endUpdates()
        // 
    }  
}
Detect a change in the number of lines of UITextView

text padding

textContainerInset property allows to set text padding for UITextView. Default value is (8, 0, 8, 0).

// set padding
textView.textContainerInset = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)

For a label and text field you need to create subclasses.

Padding for text field
Padding for UILabel