iOS Tutorial: TextField Delegate Usage (Swift + Xcode)

This entry is part 32 of 32 in the series iOS Apps

Quick example of how to use the TextFieldDelegate protocol
Limit the number of characters a user can enter
Dismiss keyboard

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var mTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mTextField.delegate = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("Allow editing")
        return true
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        print("Begin Editing")
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        print("Editing is done")
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("Enter was pressed")
        textField.resignFirstResponder()
        return true
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        let length = (textField.text?.characters.count)! + string.characters.count
        
        if length > 10 {
            return false
        } else {
            return true
        }
    }
    
    func textFieldShouldClear(textField: UITextField) -> Bool {
        print("Clear pressed")
        return true
    }
    
}

 

Series Navigation<< Tabbar and Navigation Controller
Xcode 7 Swift 2 Tutorial – Activity Indicator >>

Leave a comment

Leave a Reply