在iOS開發(fā)中,UITextField設(shè)置clearsOnBeginEditing屬性為true時,textField失去焦點再重新輸入后,輸入框會被清空。clearsOnBeginEditing屬性為false時則正常顯示。
但是如果UITextField設(shè)置了isSecureTextEntry屬性為true,則無論clearsOnBeginEditing如何設(shè)置,當(dāng)再次輸入時,輸入框都會被清空。
如果想要解決這個問題,可以在UITextField的delegate方法shouldChangeCharactersInRange中直接設(shè)置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則每次都會重復(fù)輸入。