直接上代碼
// 創(chuàng)建textField的時候,添加輸入監(jiān)聽
textField.addTarget(self, action: #selector(textDidChanged(_ :)), for: .editingChanged)
@objc func textDidChanged(_ tf: UITextField) {
if let _ = tf.text {
if let positionRange = tf.markedTextRange {
if let _ = tf.position(from: positionRange.start, offset: 0) {
// 正在輸入,不校驗(yàn)
} else {
if let text = tf.text, text.count > self.maxCount {
tf.text = (text as NSString).substring(to: 8)
}
}
} else {
// 非鍵盤輸入
if let text = tf.text, text.count > self.maxCount {
tf.text = (text as NSString).substring(to: 8)
}
}
}
Log("當(dāng)前輸入的內(nèi)容:\(tf.text ?? "")")
}