在iOS开发中,UITextField
设置clearsOnBeginEditing
属性为true
时,textField
失去焦点再重新输入后,输入框会被清空。clearsOnBeginEditing
属性为false
时则正常显示。
但是如果UITextField
设置了isSecureTextEntry
属性为true
,则无论clearsOnBeginEditing
如何设置,当再次输入时,输入框都会被清空。
如果想要解决这个问题,可以在UITextField的delegate
方法shouldChangeCharactersInRange
中直接设置textField的text
,并返回false
。
以下分别附Swift和OC代码:
Swift:
let textField = UITextField(frame: CGRect(x: 50, y: 100, width: 200, height: 50))
textField.borderStyle = .roundedRect
textField.isSecureTextEntry = true
textField.delegate = self
view.addSubview(textField)
//MARK: - UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString = (textField.text ?? "") as NSString
let tobeString = currentString.replacingCharacters(in: range, with: string)
textField.text = tobeString
return false
}
oc:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 50)];
[textField setBorderStyle:UITextBorderStyleRoundedRect];
textField.delegate = self;
[textField setSecureTextEntry:YES];
[self.view addSubview:textField];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *tobeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.text = tobeString;
return NO;
}
注意:shouldChangeCharactersInRange
方法中必须return false
,如果return true
则每次都会重复输入。