How to do a live UITextField count while typing (Swift)?

后端 未结 10 1238
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:37

I would like to count the character when user keep typing in UITextField with swift.

Image of Field and Label:

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 14:17

    This will only allow your textfield input 14 char

    class ViewController: UIViewController,UITextFieldDelegate {
    
    @IBOutlet weak var textfield: UITextField!
    @IBOutlet weak var label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = "14"
        self.textfield.delegate = self
    }
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
        if(newLength <= 14){
            self.label.text = "\(14 - newLength)"
            return true
        }else{
            return false
        }
    }
    }
    

    And Screenshot

    enter image description here

提交回复
热议问题