TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SWIFT

Swift UITextView Example

UITextView. An email requires multiple lines of text. So does a message on a website. With a UITextView we have a multiline text field in iOS.
First steps. Create a new Single View Application in Xcode and drag a UITextView to it. Please note that a UITextField is a different control that handles just one line of text input.
Add Outlet. Press control and drag the UITextView to the ViewController code window. This will allow you to create an outlet for it.
Add Button. For our tutorial we will want a UIButton. This can be added to the same Storyboard as the UITextView. When clicked, it will count the text characters entered.UIButton
Add code. Here is our source code so far. We have two IBOutlet fields that reference our UITextView and our UIButton. We add an "Action Triggered" event handler for the button.
Example UITextView: Swift // // ViewController.swift // ExampleTimeH // // ... // import UIKit class ViewController: UIViewController { @IBOutlet weak var simpleTextView: UITextView! @IBOutlet weak var simpleButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func actionTriggered(sender: AnyObject) { } }
Implement action triggered. Here we add some Swift code to the actionTriggered method. This method accesses the "text" property from the UITextView.

Count: We count the characters entered in the UITextView and store this in the "count" local.

SetTitle: We invoke the setTitle() method on the UIButton outlet. We set the text to the count of characters in the text view.

Example UIButton, UITextView: Swift // // ViewController.swift // ExampleTimeH // // ... // import UIKit class ViewController: UIViewController { @IBOutlet weak var simpleTextView: UITextView! @IBOutlet weak var simpleButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func actionTriggered(sender: AnyObject) { // The button was clicked. // Get characters count from UITextView. let count = simpleTextView.text.characters.count // Change title of the UIButton. simpleButton.setTitle("Chars \(count)", forState: UIControlState.Normal) } }
Run simulator. No we have the moment of truth. Run the iOS simulator and the default "Lorem ipsum" text will appear. Change it to something else.

ACB-def: I used the first 6 letters of the alphabet with a hyphen in between and then clicked the button. The button now reads "Chars: 7."

A review. With a UITextView we can handle an input of multiple lines of text. With the "text" property we can access this text as a String. A button can act upon the text view.
© TheDeveloperBlog.com
The Dev Codes