First touching — Swift delegate

Fei Hsiung
3 min readJul 20, 2016

--

The new topic of the class of Peter Pan’s iOS Swift this Monday is how to use delegate. Today I’m going to show you how to use functions in “UITextFieldDelegate” to handle events.

Today’s challenge is to setup a textfield, and the rule is we can only insert 10 characters into the textfield, In addition, there have to be a label to display how many charactors could me insert. Because today’s point is not on the storyboard, so I directly jump to the viewController. First, I let the class implementing UITextFieldDelegate, so I can use functions in the delegate to handle the insert event.

class ViewController: UIViewController, UITextFieldDelegate {

Then go to storyboard, right click the mouse and drag the delegate to the viewController.

This is the function I use in this practice.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}

Now back to the viewController and started insert codes. You can see those annotations on each line.

import UIKitclass ViewController: UIViewController, UITextFieldDelegate {@IBOutlet weak var countDownLabel: UILabel!@IBOutlet weak var insertTxt: UITextField!let limitCHTs = 10 //set the limit of characters 
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {let oldLength = textField.text?.characters.count //get text length brfore intertlet insertLength = string.characters.count // get inserting text lenghtlet newLength = oldLength! + insertLength - range.length //calculate text length after insertlet isWithinLimit = newLength <= limitCHTs //to see is the final lenght exceed the limitif isWithinLimit {countDownLabel.text = String(limitCHTs - newLength) //change the label's text}return isWithinLimit}func textFieldShouldReturn(_ textField: UITextField) -> Bool {self.insertTxt.resignFirstResponder() //close the keyboard when press return buttonreturn true}override func viewDidLoad() {super.viewDidLoad()self.insertTxt.delegate = selfcountDownLabel.text = String(limitCHTs) //set the initial value of the countdown label}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}

Now let us move to the textview. In UITextViewDelegate, there is a simillar function to handle the insert event for textview item, and you can see the following codes, acoording to that both paragraph of codes are almost same, only the name of the variable “String” changed to “text”, so I did not wright annotation in this paragraph.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {let oldLength = textView.text.characters.countlet insertLength = text.characters.countlet newLength = oldLength + insertLength - range.lengthlet isWhthinLimit = newLength <= limitCHTsif isWhthinLimit {countDownLabelTV.text = String(limitCHTs - newLength)}return isWhthinLimit}func textFieldShouldReturn(_ textField: UITextField) -> Bool {self.insertTxt.resignFirstResponder()return true}

The most important point in this practice is how to handle with backspace and paste event, to handle with backspace button, we can use range.length in the function, if you research the api document, it will show you that when users pressing the backspace button, the system will consider it as a range 1 insert(other buttons are 0), and replace the character or space by a “”, in case of paste, we have to know that users may paste over 1 character(as many as they want), so we have to calculate the number of total characters might have in the textfield, and to see is this paste event legal.

If you want learn more about this practice, you can see my github

https://github.com/imbearfly/HW8.git

--

--

Fei Hsiung

Located in Taipei Taiwan. Learning iOS developing by swift