Recently do the project encountered a need to do a password display and hide function, simple from the function is relatively simple, but, iOS has a disgusting bug, that is, after switching the password to hide the password when the input was emptied, this is very unfriendly, in order to solve this problem, I found on the Internet related articles, Got some inspiration, solve this problem, here to share out to provide reference and learning!
The code is as follows:
Importuikit
Class mytextfield:uitextfield,uitextfielddelegate{
private Var maxlength=11
Overrideinit (Frame:cgrect) {
Super.init (Frame:frame)
Self.delegate=self
}
Requiredinit? (Coder Adecoder:nscoder) {
Super.init (Coder:adecoder)
Self.delegate=self
}
Listen for changes in input values
Functextfield (_textfield:uitextfield, Shouldchangecharactersin range:nsrange, replacementstring string:String)- >bool{
Letnewtext = NSString (string:textfield.text!). Replacingcharacters (In:range, with:string)
Control input length
if (NewText.characters.count) >maxlength{
Letidx =self.text? Index (text?. StartIndex)!, Offsetby:maxlength)
Self.text=self.text?. SUBSTRING (to:idx!)
return False
}
Input not emptied when handling plaintext redaction (critical code)
If textfield==self&&self.issecuretextentry{
Self.text=newtext
return False
}
return True
}
Set the maximum length that can be entered
Func setmaxlength (maxlength:int) {
Self.maxlength=maxlength
}
}
The code is posted here, if there is any problem welcome to communicate!
IOS Swift implements password display and hiding