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 iOS application, and how to response user action ( such as click return key, begin editing ) on those controls.

1. UITextField & UITextView Example.

This example contains one UITextField and one UITextView. All the controls has hint text. When you click the control, the hit text will disappear. And when you begin edit the control or click return key in keyboard, it will print out some message in the Xcode console to tell you which method is invoked.

screen when the ios app startscreen after user input text in the text field and text view

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.

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.

3. Add UI Controls.

  1. Create a Xcode project with name TextFieldTextViewExample.
  2. Open Main.storyboard file and add two UILabel and one UITextField, one UITextView control in to the main view.
    add two label one textfield one textview in main storyboard
  3. Select the UITextField control, and input the Placeholder text and select the Clear Button style in the right Show the Attributes inspector panel. These two settings will display the hint text in the control, and display a delete button at the end of the input text box when user input text.
    config textfield placeholder and clear button
  4. Select the UITextView control, and input the default text in it’s Show the Attributes inspector panel Text View section also.
    input text view text in show the attributes inspector panel

4. Add TextField & TextView Event Delegator.

Now all the UI controls have been added. We should add text field and text view event delegator to process the UI event in IB.

  1. Right click the UITextField, 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.
    set viewcontroller as textfiled delegator
READ :   How To Set iOS App Icon In Xcode Project

5. Main.storyboard File.

In fact the Main.storyboard file is a xml file, you can right click the file in Project navigator, then click Open As —> Source Code menu item in the popup menu. The xml version will popup. 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 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>

6. Edit View Controller Source Code.

To be UITextField and UITextView delegator, ViewController class must implements UITextFieldDelegate, UITextViewDelegate. Then you can override the delegate functions to response to the control events. The delegate functions used in this example are textFieldShouldReturntextViewtextFieldDidBeginEditing, textViewDidBeginEditing.

READ :   iOS Auto Layout With Constraint Example

ViewController.swift

//
//  ViewController.swift
//  TextFieldTextViewExample
//
//  Created by zhao song on 2018/8/5.
//  Copyright © 2018 dev2qa.com. All rights reserved.
//

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.

        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

    }
}

This is all the content about this example, in next article, i will tell you how to implement this example in source code instead of using the IB.

(Visited 628 times, 3 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

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