需求:指定輸入框只能輸入數(shù)字,指定輸入框只能輸入字母
- 設(shè)置相應(yīng)輸入框的鍵盤類型指定為數(shù)字或字母
areaCell?.rightTextField.keyboardType = .numberPad
areaCell?.rightTextField.keyboardType = .default
2.輸入格式錯(cuò)誤時(shí),彈出錯(cuò)誤提示
fileprivate func allowNumber(_ string: String) -> Bool {
// 通過(guò)正則來(lái)判斷是否為數(shù)字
let regex = "^[0-9]*$" // 正則表達(dá)式
let pred = NSPredicate.init(format: "SELF MATCHES %@", regex)
return pred.evaluate(with: string)
}
fileprivate func allowAlphabet(_ string: String) -> Bool {
// 通過(guò)正則來(lái)判斷是否為字母
let regex = "^[a-zA-Z]*$" // 正則表達(dá)式
let pred = NSPredicate.init(format: "SELF MATCHES %@", regex)
return pred.evaluate(with: string)
}
校驗(yàn)按鈕點(diǎn)擊,調(diào)用校驗(yàn)的方法
@IBAction func checkInputTextAction(_ sender: Any) {
if let string = self.inputTextField.text {
if self.numberBtn.isSelected {
if self.allowNumber(string) {
debugPrint("")
} else {
debugPrint("只允許輸入數(shù)字")
}
} else if self.alphabetBtn.isSelected {
if self.allowAlphabet(string) {
debugPrint("")
} else {
debugPrint("只允許輸入字母")
}
}
}
}