ใช้ UITextFieldDelegate อ่านรายละเอียด
ตัวอย่าง: แสดงจำนวนตัวอักษรขณะพิมพ์
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → New Project → Single View Application → ชื่อ "TextFieldCount"
ขั้นตอนที่ 2: ออกแบบ UI
Main.storyboard: TextField + Label @IBOutlet: txtInputBox, lblCount

ขั้นตอนที่ 3: Conform Protocol และตั้ง Delegate
class ViewController: UIViewController, UITextFieldDelegate {
txtInputBox.delegate = self
}ขั้นตอนที่ 4: Implement shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == txtInputBox {
let strLength = textField.text?.count ?? 0
let lngthToAdd = string.count
let lengthCount = strLength + lngthToAdd
self.lblCount.text = "\(lengthCount)"
}
return true
}ขั้นตอนที่ 5: รันทดสอบ
โค้ดเต็ม:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var txtInputBox: UITextField!
@IBOutlet var lblCount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
txtInputBox.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == txtInputBox {
let strLength = textField.text?.count ?? 0
let lngthToAdd = string.count
let lengthCount = strLength + lngthToAdd
self.lblCount.text = "\(lengthCount)"
}
return true
}
}
