Set the maximum characters allowed to type from the User for TextField in iOS Swift


We can set the maximum allowed characters to get the input from the user in swift.First, we have to add the delegate to the class.
Code:
class ViewController: UIViewController,UITextFieldDelegate {
}


We have to set the delegate to the text field in Storyboard or via code.
                TextField.delegate = self
Then implement the below method to control the input from the user.


// #MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        guard let text = textField.text else { return true }
        let newLength = text.utf16.count + string.utf16.count - range.length
            return newLength <= 64
        // Bool
    }


The above I had put the maximum character count as 64.

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift