iOS UITextField And UITextView Swift Example

UITextField can be used to display a one-line text editor input box. While UITextView can be used to display a multiple-line text area, it can be either editable or read-only. This example will show you how to add text filed and text view in the iOS application, and how to respond to user action ( such as click return key, begin editing ) on those controls.

1. UITextField & UITextView Example.

  1. This example contains one UITextField and one UITextView. All the controls have hint text.
  2. When you click the control, the hint text will disappear.
  3. And when you begin to edit the control or click the return key on the keyboard, it will print out some message in the Xcode console to tell you which method is invoked.
    screen-when-the-ios-app-start
  4. Below is the Xcode console output.
    2018-08-05 21:29:14.657023+0800 TextFieldTextViewExample[7076:283142] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
    
    2018-08-05 21:29:37.746721+0800 TextFieldTextViewExample[7076:283142] TextField textFieldDidBeginEditing method triggered.
    
    2018-08-05 21:29:37.750920+0800 TextFieldTextViewExample[7076:283142] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/zhaosong/Library/Developer/CoreSimulator/Devices/C162420B-9B20-44C4-8FE3-4F1DFDBBE2E8/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
    
    2018-08-05 21:29:37.751542+0800 TextFieldTextViewExample[7076:283142] [MC] Reading from private effective user settings.
    
    2018-08-05 21:29:43.588027+0800 TextFieldTextViewExample[7076:283142] TextView textViewDidBeginEditing method triggered.
    
    2018-08-05 21:29:54.923305+0800 TextFieldTextViewExample[7076:283142] TextView textView method triggered and the input text is ''.

2. Use Interface Builder To Implement This Example.

  1. There are two methods to implement this example, the first one is to use IB( interface builder), the second one is to use source code. Now I will introduce how to implement it in IB.

2.1. Add UI Controls.

  1. Create an Xcode project with the name TextFieldTextViewExample.
  2. Open the Main.storyboard file and add two UILabel and one UITextField, one UITextView control into the main view like below.
    add-two-label-one-textfield-one-textview-in-main-storyboard
  3. Select the UITextField control, click Show the Attributes inspector icon in right panel’s top tab bar, then in the Text Field section, input the Placeholder ( hint ) text ( I use Input job title in this example ) after Placeholder item label, and select the Clear Button style in the drop-down list after Clear Button item label, there are four clear button styles, I choose Is always visible. These two settings will display the hint text in the control, and display a clear button at the end of the input text box when the user inputs text.
    config-textfield-placeholder-and-clear-button
  4. Select the UITextView control, click Show the Attributes inspector icon in the right panel’s top tab bar. Then in the Text View section, select Plain from the Text drop-down list, and input the hint text such as Input the job description in the input text box under the Text drop-down list.
    input-text-view-text-in-show-the-attributes-inspector-panel

3. Add TextField & TextView Event Delegator.

  1. Now all the UI controls have been added. We should add a text field and text view event delegator to process the UI event in IB.
  2. Right-click the UITextField control object, drag the plus icon behind the Outlets —> delegate item, a blue line will appear, drag and drop the blue line to the View Controller and release the mouse button. Then View Controller class has just be added as the text field delegator. Do the same to the text view control. You can see this step demo video on URL https://youtu.be/sjkjFsW70Ds.
  3. After the above action, you can click the UITextField item ( Input job title ) to select it, then click the Show the Connection inspector icon at Xcode right inspector panel, then you can see the delegate —> View Controller relationship under the Outlets section.

4. Main.storyboard File.

  1. In fact the Main.storyboard file is an XML file, you can right-click the file in Project navigator, then click Open As —> Source Code menu item in the popup menu. It will display the Main.storyboard file’s XML source code.
  2. Below is the Main.storyboard XML content of this example. If you are familiar with android app development, you can find this file is similar to the main_layout.xml file in android.
    <?xml version="1.0" encoding="UTF-8"?>
    <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14306.4" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
        <device id="retina4_7" orientation="portrait">
            <adaptation id="fullscreen"/>
        </device>
        <dependencies>
            <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14278.2"/>
            <capability name="Safe area layout guides" minToolsVersion="9.0"/>
            <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
        </dependencies>
        <scenes>
            <!--View Controller-->
            <scene sceneID="tne-QT-ifu">
                <objects>
                    <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="TextFieldTextViewExample" customModuleProvider="target" sceneMemberID="viewController">
                        <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                            <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                            <subviews>
                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Job Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="tw1-d5-hM2">
                                    <rect key="frame" x="67" y="112" width="66" height="21"/>
                                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                    <nil key="textColor"/>
                                    <nil key="highlightedColor"/>
                                </label>
                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Job Description" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="eif-kU-lgR">
                                    <rect key="frame" x="67" y="187" width="121" height="21"/>
                                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                    <nil key="textColor"/>
                                    <nil key="highlightedColor"/>
                                </label>
                                <textField opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Input job title." textAlignment="natural" minimumFontSize="17" clearButtonMode="always" translatesAutoresizingMaskIntoConstraints="NO" id="1kZ-YG-LoT">
                                    <rect key="frame" x="67" y="141" width="235" height="30"/>
                                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                    <nil key="textColor"/>
                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                    <textInputTraits key="textInputTraits"/>
                                    <connections>
                                        <outlet property="delegate" destination="BYZ-38-t0r" id="HtS-8y-T69"/>
                                    </connections>
                                </textField>
                                <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" fixedFrame="YES" text="Input the job description" textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="vgM-ZT-Oqo">
                                    <rect key="frame" x="65" y="217" width="240" height="128"/>
                                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                    <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                    <connections>
                                        <outlet property="delegate" destination="BYZ-38-t0r" id="8sb-4j-fVO"/>
                                    </connections>
                                </textView>
                            </subviews>
                            <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                            <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
                        </view>
                    </viewController>
                    <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
                </objects>
                <point key="canvasLocation" x="117.59999999999999" y="118.29085457271366"/>
            </scene>
        </scenes>
    </document>

5. Edit View Controller Source Code.

  1. To be UITextField and UITextView delegator, ViewController class must implements UITextFieldDelegate, UITextViewDelegate. Then you can override the delegate functions to respond to the control events.
  2. The delegate functions used in this example are textFieldShouldReturntextViewtextFieldDidBeginEditing, textViewDidBeginEditing.
  3. Below is the source code of the file ViewController.swift
    import UIKit
    
    class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        /* Below method is inherited from UITextFieldDelegate, it will be invoked when text filed get focus and click return key. */
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
            NSLog("TextField textFieldShouldReturn method triggered.")
            return true
        }
    
        /* Below method is inherited from UITextViewDelegate, it will be invoked when text view content is changed. */
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
            if(text == "\n")
            {
               NSLog("TextView textView method triggered and the input text is '\n'.")
            }
            return true
        }
    
        /* Invoked when first edit the textfield control. */
        func textFieldDidBeginEditing(_ textField: UITextField) {
    
            NSLog("TextField textFieldDidBeginEditing method triggered.")
    
            // Clear the default text. If you do not write below code, then the hint text will be clear when you input the first character.
    
            textField.placeholder = nil
    
        }
    
        /* Invoked when first edit the textview control. */
        func textViewDidBeginEditing(_ textView: UITextView) {
    
            NSLog("TextView textViewDidBeginEditing method triggered.")
    
            // Clear the default text.
            textView.text = nil
    
        }
    }
  4. This is all the content about this example, in the next article, I will tell you how to implement this example in source code instead of using the IB.

Reference

  1. How To Use UITextField And UITextView In Swift Programmatically Example
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x