代码之家  ›  专栏  ›  技术社区  ›  mrTalaq

UItextfield编辑和响应

  •  1
  • mrTalaq  · 技术社区  · 8 年前

    嗨,问题是我已经将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
        }
    
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Vanita L.    8 年前

    在你的发髻动作中

    @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)
        }
    }