iOS关于UITextField的clearsOnBeginEd

2021-06-08  本文已影响0人  剑老师

在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则每次都会重复输入。

上一篇下一篇

猜你喜欢

热点阅读