How to you set the maximum number of characters that can be entered into a UITextField using swift?

社会主义新天地 提交于 2019-12-08 05:04:28

问题


How do you limit the number of characters in a UITextField to 10, and if the user enters more than 10, only record the first 10 characters?


回答1:


This solution deals with a user pasting text or tapping delete key too.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let length = count(textField.text.utf16) + count(string.utf16) - range.length

    return length <= 10 

}



回答2:


You can check the text before it gets displayed by implementing the UITextFieldDelegate.

class ViewController: UIViewController, UITextFieldDelegate {

    textField(textField: UITextField!,
    shouldChangeCharactersInRange range: NSRange,
                replacementString string: String!) -> Bool {

        var shouldChange = false

        if countElements(textField.text) < 10 { 
            shouldChange = true
        }

        return shouldChange
    }
}


来源:https://stackoverflow.com/questions/24641982/how-to-you-set-the-maximum-number-of-characters-that-can-be-entered-into-a-uitex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!