In the iOS development process, we sometimes need to control the input length of the Uitextfield, such as the maximum length of the input mobile phone number 11 bits, and iOS itself is not like Android can set input box input length, followed by a few simple steps to achieve this function:
1. Create a new class to continue Uitextfield such as this class called Myuitextfield
2. Declare a variable to record the maximum length of the input
3. Add an event to listen for changes in input box input values
4. Intercept the string by judging whether the length of the current text string is greater than the maximum length and assign a value to the current text to guarantee that the value of the text string starts with the specified maximum length
The code is as follows:
Import UIKit
Class MyTextField: uitextfield{
The maximum length of the Var maxlength=11//can be entered
override init(frame: cgrect) {
Super. Init(frame:frame)
self. Addevent()
}
Required init? ( Coder Adecoder: nscoder) {
Super. Init(coder:adecoder)
self. Addevent()
}
// Add event to listen for changes in input box values
func addevent () {
self. AddTarget(self, action: #selector(valuechage), for:. editingchanged)
}
// limit input length of input box
func valuechage () {
if (self. Text?. characters. Count)!>maxLength{
let idx = self. Text?. index(text?. startIndex)!, Offsetby: maxLength)
self. Text=self. Text?. substring(to:idx!)
}
}
}
Simple steps for IOS uitextfield input length control