UItextfield编辑和响应

问题描述 投票:1回答:1

嗨问题是我已经将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
    }


}
ios iphone swift
1个回答
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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.