We have introduced how to use UITextField and UITextView in the article iOS UITextField And UITextView Swift Example. In that article, we use interface builder and storyboard to create the user interface, assign delegate protocol to the view controller, implement delegate methods to respond to user action ( for example: begin editing a text field, etc.). In this article we will implement it again all use swift source code programmatically.
1. Implement UITextField & UITextView Example With Swift Source Code Programmatically Steps.
- Create an Xcode project using the single view app template. Below is the project’s files list panel.
TextFieldTextViewExampleImplUseCode TextFieldTextViewExampleImplUseCode AppDelegate.swift SceneDelegate.swift ViewController.swift Main.storyboard Assets.xcassets LaunchScreen.storyboard Info.plist
- Because my Xcode’s version is 11, so it will use SceneDelegate to manage the UI lifecycle. But this is not the issue, if you are interested in it, please read article Swift Xcode 11 iOS 13 Scene Delegate Life Cycle Example.
- What we need to do is just edit the ViewController.swift file and the ViewController class in this file.
- First the ViewController class should implement two delegate protocols UITextFieldDelegate and UITextViewDelegate. The delegate protocol is something like a java interface. Then you can implement the functions defined in the two delegate protocol.
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate
- Set one UITextField and one UITextView type object as this class’s instance variable.
// This is job title UITextField object. var jobTitleTextField:UITextField = UITextField() // This is job description UITextView object. var jobDescTextView:UITextView = UITextView()
- Add two function addJobTitleLabelAndTextField and addJobDescLabelAndTextView. The first function will add a job title label and a UITextField for users to input the job title. The second function will add a job description label and a UITextView for users to input the job descriptions.
- Because the ViewController class has implemented two delegate protocol UITextFieldDelegate and UITextViewDelegate, so you can override below protocol functions. You can see the source code comments in ViewController.swift file for detailed function introduction.
textField, textFieldDidBeginEditing, textFieldShouldReturn, textView, textViewDidBeginEditing, textViewDidEndEditing
- Below is the full source code of ViewController.swift file.
// // ViewController.swift // TextFieldTextViewExampleImplUseCode // // Created by song zhao on 11/7/19. // Copyright © 2019 dev2qa.com. All rights reserved. // import UIKit // Make ViewController class implement UITextFieldDelegate, UITextViewDelegate delegate protocol. class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { // Define vertical space distance between label and text field or text view item. let itemVerticalSpace:CGFloat = 30 // Get screen size, width and height value. let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height // Set job title text field's width and height value. let jobTitleTextFieldWidth:CGFloat = 200 let jobTitleTextFieldHeight:CGFloat = 30 // Set job description text view's width and height value. let jobDescTextViewWidth:CGFloat = 200 let jobDescTextViewHeight:CGFloat = 300 // This is job title UITextField object. var jobTitleTextField:UITextField = UITextField() // This is job description UITextView object. var jobDescTextView:UITextView = UITextView() override func viewDidLoad() { super.viewDidLoad() addJobTitleLabelAndTextField() addJobDescLabelAndTextView() } /* This function will create and add job title label and text field to screen. */ func addJobTitleLabelAndTextField(){ // Set text field width, height and x,y location value of top left point. let jobTitleTextFieldX:CGFloat = (screenWidth - jobTitleTextFieldWidth)/2 let jobTitleTextFieldY:CGFloat = screenHeight / 5 // Calculate the text field frame as a CGRect object. let jobTitleTextFieldFrame:CGRect = CGRect(x: jobTitleTextFieldX, y: jobTitleTextFieldY, width: jobTitleTextFieldWidth, height: jobTitleTextFieldHeight) // Create the UITextField object. jobTitleTextField = UITextField(frame: jobTitleTextFieldFrame) // Set the UITextField object's border style. jobTitleTextField.borderStyle = UITextField.BorderStyle.roundedRect // Set this ViewController object as the UITextField object's delegate. jobTitleTextField.delegate = self // Set UITextField object's placeholder and clear button mode. jobTitleTextField.placeholder = "Input job title" jobTitleTextField.clearButtonMode = UITextField.ViewMode.always // Set job title label top-left point x, y location. X value is same as jobTitleTextField's top-left point's x value. let jobTitleLabelX:CGFloat = jobTitleTextField.frame.origin.x // Y value is jobTitleTextField's top-left point's y value minus the space constant variable value. let jobTitleLabelY:CGFloat = jobTitleTextField.frame.origin.y - itemVerticalSpace // Job title label's width and height is same with jobTitleTextField. let jobTitleLabelWidth:CGFloat = jobTitleTextField.bounds.width let jobTitleLabelHeight:CGFloat = jobTitleTextField.bounds.height // Create job title label frame CGRect object. let jobTitleLabelRect:CGRect = CGRect(x: jobTitleLabelX, y: jobTitleLabelY, width: jobTitleLabelWidth, height: jobTitleLabelHeight) // Create job title UILabel object. let jobTitleLabel:UILabel = UILabel(frame: jobTitleLabelRect) // Set job title label text. jobTitleLabel.text = "Job Title" // Add job title label to the root view object. self.view.addSubview(jobTitleLabel) // Add job title text field as root view's sub view. self.view.addSubview(jobTitleTextField) } /* This function will create and add job description label and text view to screen. */ func addJobDescLabelAndTextView(){ // Set text view width, height and x,y location value of top left point. let jobDescTextViewX:CGFloat = (screenWidth - jobDescTextViewWidth)/2 let jobDescTextViewY:CGFloat = jobTitleTextField.frame.origin.y + 3 * itemVerticalSpace // Calculate the text view frame as a CGRect object. let jobDescTextViewFrame:CGRect = CGRect(x: jobDescTextViewX, y: jobDescTextViewY, width: jobDescTextViewWidth, height: jobDescTextViewHeight) // Create the UITextView object. jobDescTextView = UITextView(frame: jobDescTextViewFrame) // Set this ViewController object as the UITextView object's delegate. jobDescTextView.delegate = self jobDescTextView.text = "Input job description." jobDescTextView.backgroundColor = UIColor.green // Set job description label top-left point x, y location. X value is same as jobDescTextView's top-left point's x value. let jobDescLabelX:CGFloat = jobDescTextView.frame.origin.x // Y value is jobDescTextView's top-left point's y value minus the space constant variable value. let jobDescLabelY:CGFloat = jobDescTextView.frame.origin.y - itemVerticalSpace // Job description label's width and height is same with jobDescTextView. let jobDescLabelWidth:CGFloat = jobDescTextView.bounds.width let jobDescLabelHeight:CGFloat = itemVerticalSpace // Create job description label frame CGRect object. let jobDescLabelRect:CGRect = CGRect(x: jobDescLabelX, y: jobDescLabelY, width: jobDescLabelWidth, height: jobDescLabelHeight) // Create job description UILabel object. let jobDescLabel:UILabel = UILabel(frame: jobDescLabelRect) // Set job description label text. jobDescLabel.text = "Job Description" // Add job description label to the root view object. self.view.addSubview(jobDescLabel) // Add job description text view as root view's sub view. self.view.addSubview(jobDescTextView) } // This function will be called when the textField object( jobTitleTextField ) begin editing. func textFieldDidBeginEditing(_ textField: UITextField) { print("textFieldDidBeginEditing") } // This function is called when you click return key in the text field. func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("textFieldShouldReturn") return true } // This function is called when you input text in the textfield. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print("textField") print("input text is : \(string)") return true } // This function is called when you input text in the textView. func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{ print("textView.") print("input text is : \(text)") return true } // This function is called when you begin edit text view. func textViewDidBeginEditing(_ textView: UITextView) { textView.text = "" print("textViewDidBeginEditing") } // This function is called when you stop edit in the text view, such as change mouse focus to the text field input box. func textViewDidEndEditing(_ textView: UITextView) { print("textViewDidEndEditing") } }
- When you run the example and input text in the UITextField or UITextView, you can see below output message in Xcode debug console.
textFieldDidBeginEditing textField input text is : H textField input text is : i textFieldShouldReturn textViewDidBeginEditing textView. input text is : H textView. input text is : a textView. input text is :
- Below is the iOS simulator screen when you run the example app.
- If you find the virtual keyboard do not popup in the iOS simulator, you can read article How To Fix Xcode iOS Simulator App Do Not Display Keyboard Automatically Error to learn more.
Reference