iOS關(guān)于UITextField的clearsOnBeginEditing屬性失效問題解決方案

在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ù)輸入。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容