通常滔驶,我們?cè)陂_(kāi)發(fā)一個(gè)app時(shí)登錄組冊(cè)界面均為textField的輸入答姥。然而,我們的手機(jī)號(hào)及驗(yàn)證碼的位數(shù)是固定的闹丐,那我我們就有必要限制textField的輸入字符串的長(zhǎng)度,通常的做法如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField isEqual:self.phoneNumberTextField]) {
return textField.text.length < 11;
}
else if ([textField isEqual:self.verificationCodeTextField]) {
return textField.text.length < 6;
}
else if ([textField isEqual:self.passwordTextField]) {
return textField.text.length < 16;
}
return YES;
}
如果我們按照上面的方式寫(xiě)的話被因,當(dāng)我們的手機(jī)號(hào)輸入11位之后卿拴,鍵盤(pán)的刪除按鈕就失效了衫仑,但,只要改成下面這樣就可以了:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (range.length == 1 && string.length == 0) {
return YES;
}
else if ([textField isEqual:self.phoneNumberTextField]) {
return textField.text.length < 11;
}
else if ([textField isEqual:self.verificationCodeTextField]) {
return textField.text.length < 6;
}
else if ([textField isEqual:self.passwordTextField]) {
return textField.text.length < 16;
}
return YES;
}
有沒(méi)有幫到你呢堕花?