基于swift5.0实现
希望能帮到各位
let changeNameField = CustomTextField()
changeNameField.backgroundColor = .white
changeNameField.text = nameStr
changeNameField.delegate = self
changeNameField.keyboardType = .default
changeNameField.clearButtonMode = .always
changeNameField.borderStyle = .none
changeNameField.becomeFirstResponder()//弹出输入键盘
changeNameField.returnKeyType = .done
changeNameField.cstmDelegate = self
changeNameField.addTarget(self, action: #selector(textFieldChangeMessage), for: .editingChanged)
whiteView.addSubview(changeNameField)
changeNameField.snp.makeConstraints { make in
make.left.equalTo(10)
make.right.equalTo(-10)
make.height.equalTo(50)
}
import UIKit
protocol CustomTextFiledDelegate {
func customDeleteBackward(_ textField:UITextField)
}
class CustomTextField : UITextField {
var cstmDelegate :CustomTextFiledDelegate?
override func deleteBackward() {
self.cstmDelegate?.customDeleteBackward(self)
super.deleteBackward()
}
}
func customDeleteBackward(_ textField: UITextField) {
}
- 这个方法会导致键盘按钮失效,这个方法也需还有其他的方式可以解决这个问题,如果有请@博主一起交流
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let count: Int = textField.text!.count
if (count > 15) {
return false
}else{
return true
}
}
- 我目前的解决方案是 添加监听的方法,然后替换限制后的文本为空,还可以删除限制后的文本,虽然不是很好的解决方法,但也能实现该功能,如果有好的想法可以一起交流学习,共同进步·······
程序是死的,我们要学会灵活运用,俗话说的好,条条大路通罗马·······
具体的实现方法如下
- UITextField 添加监听的方法
textField.addTarget(self, action: #selector(textFieldChangeMessage), for: .editingChanged)
//MARK: 限制输入的文本15个字符
@objc func textFieldChangeMessage(_ textField : UITextField){
let text = self.changeNameField.text!
if text.count > 15 {
var text = self.changeNameField.text!
//替换一段字符
let strat = text.index(text.startIndex, offsetBy: 15)
let end = text.endIndex
text = text.replacingCharacters(in: strat..<end, with: "")
self.changeNameField.text = text
}
}
@objc func textFieldChangeMessage(_ textField : UITextField){
let text = self.changeNameField.text!
if text.count > 15 {
var text = self.changeNameField.text!
// //删除一段字符
text.removeSubrange(text.index(text.startIndex, offsetBy: 15)..<text.endIndex)
self.changeNameField.text = text
}
}