1. 通知
UITextField派生自UIControl,所以UIControl類中的通知系統在文本字段中也可以使用。
除了UIControl類的標準事件,你還可以使用下列UITextField類特有的事件:
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification
當文本字段退出編輯模式時觸發,通知的object屬性存儲了最終文本。
因為文本字段要使用鍵盤輸入文字,所以下面這些事件發生時,也會發送動作通知
UIKeyboardWillShowNotification // 鍵盤顯示之前發送
UIKeyboardDidShowNotification // 鍵盤顯示之后發送
UIKeyboardWillHideNotification // 鍵盤隱藏之前發送
UIKeyboardDidHideNotification // 鍵盤隱藏之后發送
2. 限制只能輸入特定的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *limitStr = @"0123456789\n";
NSCharacterSet *characterSet= [[NSCharacterSet characterSetWithCharactersInString:limitStr] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
BOOL canChange = [string isEqualToString:filtered];
return canChange;
}
”0123456789\n” (代表可以輸入數字和換行,請注意這個\n,如果不寫這個,Done按鍵將不會觸發.如果用在SearchBar中,將會不觸發Search事件,因為你自己限制不讓輸入\n。)
當然,你還可以在以上方法return之前,提示用戶只能輸入數字。
3. 限制只能輸入一定長度的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
// string為此時輸入的那個字符
// 返回YES就是可以改變輸入框的值,NO相反
if ([string isEqualToString:@"\n"]) {
return YES;
}
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// 如果輸入框內容大于20則彈出警告
if ([toBeString length] > 20) {
textField.text = [toBeString substringToIndex:20];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"最多不能超過20字" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
return YES;
}