One approach to ensure that a UITextField only accepts integers and a maximum of 10 digits in Swift 5 is to use the UITextFieldDelegate and implement the shouldChangeCharactersIn method.
Here's an example implementation:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var numberTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// set delegate to self
numberTextField.delegate = self
}
// UITextFieldDelegate method to limit input to integers and max 10 characters
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// get the new string after adding the replacement string
let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
// output the new string for debugging purposes
print("new string: \(newString)")
// check if the new string is a valid integer and has max 10 digits
if let _ = Int(newString), newString.count <= 10 {
return true
} else {
return false
}
}
}
In this implementation, we set the view controller as the delegate for the numberTextField and implement the UITextFieldDelegate method shouldChangeCharactersIn.
Inside this method, we first get the new string by replacing the string in the specified range with the replacement string. We then check if this new string is a valid integer and has a maximum of 10 digits. If it meets these criteria, we allow the change to be made, otherwise we block it.
Note that we also included a print statement to output the new string for debugging purposes. You can remove this line in your implementation.
Using this implementation, the UITextField will only allow integers and a maximum of 10 digits to be inputted.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-06-20 11:00:00 +0000
Seen: 9 times
Last updated: Dec 02 '21
How to add a custom button in SwiftUI for iOS13 that enables going back between screens?
How can the update of properties from both ParentViewModel and ChildViewModel in SwiftUI be solved?
Can SwiftUI be utilized to restrict the touch region for a drag gesture?
How can the color of a selected element (Picker) be modified in SwiftUI for WatchOS?
How to make a calendar layout that is horizontal using Swiftui?
What is the process to add a radio button with a check mark on a TableView cell using Swift?
How to limit UITextField input to only accept numerical values?