嗨问题是我已经将UItextfield设置为有限的字符,但它可以正常使用iPhone键盘和我的Mac键盘,但是当我在UIView上使用数字时它会超出限制
限制代码:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField1: UITextField!
@IBAction func Botton1(_ sender: UIButton) {
textField1.text = textField1.text! + String (sender.tag)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if range.length + range.location > (textField1.text?.count)!{
return false
}
let NewLength = (textField1.text?.count)! + string.count - range.length
return NewLength < 4
}
}
答案 0 :(得分:0)
@IBAction func Botton1(_ sender: UIButton) {
textField1.text = textField1.text! + String (sender.tag)
}
更改为
@IBAction func Botton1(_ sender: UIButton) {
let range: NSRange = NSRange.init(location: 0, length: 1)
if self.textField(textField1, shouldChangeCharactersIn: range, replacementString: String(sender.tag)) {
textField1.text = textField1.text! + String (sender.tag)
}
}