直接上代码
// 创建textField的时候,添加输入监听
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) {
// 正在输入,不校验
} 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("当前输入的内容:\(tf.text ?? "")")
}