今天介紹其他 TextField 其他常見的用法
func textField(_ textField: UITextField, shoudChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return }
let count = text.count + string.count - range.length
return count <= 10
}
return count <= 限制字數
新增 TextField ,並在 viewDidLoad 幫每個 TextField 增加 tag
@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextFIeld: UITextField!
@IBOutlet weak var thirdTextField: UITextField!
@IBOutlet weak var fourthTextField: UITextField!
@IBOutlet weak var fifthTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
firstTextField.tag = 0
secondTextFIeld.tag = 1
thirdTextField.tag = 2
fourthTextField.tag = 3
fifthTextField.tag = 4
delegateAndDataSourseInit()
}
func delegateAndDataSourseInit() {
firstTextField.delegate = self
secondTextFIeld.delegate = self
thirdTextField.delegate = self
fourthTextField.delegate = self
fifthTextField.delegate = self
}
接著在 textFieldShouldReturn 的 Function 內加入以下程式碼
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
} else {
textField.resignFirstResponder()
textField.endEditing(true)
}
這樣一來, TextField 就會在使用者按下 enter 鍵之後自動跳下一行了。