Set the maximum character length of a UITextField

前端 未结 30 1702
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  误落风尘
    2020-11-22 02:45

    swift 3.0

    This code is working fine when you are paste string more than your character limits.

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            let str = (textView.text + text)
            if str.characters.count <= 10 {
                return true
            }
            textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 10))
            return false
        }
    

    Thanks for your votes. :)

提交回复
热议问题