UITextField 是 iOS 中最常用的輸入控件之一。本文系統整理它的屬性、代理方法與常見用法,並附上大量程式碼範例,方便隨時查閱。
// 初始化 textfield 並設置位置及大小
UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)];
// 設置邊框樣式,只有設置了才會顯示
text.borderStyle = UITextBorderStyleRoundedRect;
typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
} UITextBorderStyle;
// 設置背景色(若使用自定義背景圖片,邊框會被忽略)
text.backgroundColor = [UIColor whiteColor];
// 設置背景圖
text.background = [UIImage imageNamed:@"dd.png"];
// 設置禁用狀態的背景圖
text.disabledBackground = [UIImage imageNamed:@"cc.png"];
// 沒有內容時顯示的水印提示
text.placeholder = @"password";
// 設置內容字體樣式與大小
text.font = [UIFont fontWithName:@"Arial" size:20.0f];
// 設置字體顏色
text.textColor = [UIColor redColor];
// 清除按鈕(叉號)出現的時機,用於一鍵清空內容
text.clearButtonMode = UITextFieldViewModeAlways;
typedef enum {
UITextFieldViewModeNever, // 從不出現
UITextFieldViewModeWhileEditing, // 編輯時出現
UITextFieldViewModeUnlessEditing,// 除編輯外都出現
UITextFieldViewModeAlways // 一直出現
} UITextFieldViewMode;
// 一開始就存在的文字
text.text = @"一開始就在輸入框的文字";
// 每輸入一個字符就變成點,用於密碼輸入
text.secureTextEntry = YES;
// 是否自動糾錯
text.autocorrectionType = UITextAutocorrectionTypeNo;
typedef enum {
UITextAutocorrectionTypeDefault, // 默認
UITextAutocorrectionTypeNo, // 不自動糾錯
UITextAutocorrectionTypeYes // 自動糾錯
} UITextAutocorrectionType;
// 再次編輯時清空內容
text.clearsOnBeginEditing = YES;
// 內容對齊方式
text.textAlignment = UITextAlignmentLeft;
// 內容的垂直對齊方式(UITextField 繼承自 UIControl)
text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
// 設為 YES 時文本會自動縮小以適應寬度,默認保持原大小並滾動
textFied.adjustsFontSizeToFitWidth = YES;
// 自動縮小顯示的最小字體大小
text.minimumFontSize = 20;
// 設置鍵盤樣式
text.keyboardType = UIKeyboardTypeNumberPad;
typedef enum {
UIKeyboardTypeDefault, // 默認鍵盤,支持所有字符
UIKeyboardTypeASCIICapable, // 支持 ASCII 的默認鍵盤
UIKeyboardTypeNumbersAndPunctuation, // 標準電話鍵盤,支持 +*#
UIKeyboardTypeURL, // URL 鍵盤,支持 .com
UIKeyboardTypeNumberPad, // 數字鍵盤
UIKeyboardTypePhonePad, // 電話鍵盤
UIKeyboardTypeNamePhonePad, // 電話鍵盤,也支持人名
UIKeyboardTypeEmailAddress, // 電子郵件鍵盤
UIKeyboardTypeDecimalPad, // 數字鍵盤,含小數點
UIKeyboardTypeTwitter, // 便於輸入 @、#
UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable,
} UIKeyboardType;
// 首字母是否大寫
text.autocapitalizationType = UITextAutocapitalizationTypeNone;
typedef enum {
UITextAutocapitalizationTypeNone, // 不自動大寫
UITextAutocapitalizationTypeWords, // 單詞首字母大寫
UITextAutocapitalizationTypeSentences, // 句子首字母大寫
UITextAutocapitalizationTypeAllCharacters // 所有字母大寫
} UITextAutocapitalizationType;
// return 鍵變成什麼鍵
text.returnKeyType = UIReturnKeyDone;
typedef enum {
UIReturnKeyDefault, // 默認,灰色按鈕,標有 Return
UIReturnKeyGo, // 標有 Go 的藍色按鈕
UIReturnKeyGoogle, // 標有 Google,用於搜索
UIReturnKeyJoin, // 標有 Join
UIReturnKeyNext, // 標有 Next
UIReturnKeyRoute, // 標有 Route
UIReturnKeySearch, // 標有 Search
UIReturnKeySend, // 標有 Send
UIReturnKeyYahoo, // 標有 Yahoo
UIReturnKeyEmergencyCall // 緊急呼叫按鈕
} UIReturnKeyType;
// 鍵盤外觀
textView.keyboardAppearance = UIKeyboardAppearanceDefault;
typedef enum {
UIKeyboardAppearanceDefault, // 默認外觀,淺灰色
UIKeyboardAppearanceAlert // 深灰、石墨色
} UIKeyboardAppearance;
// 設置代理,用於實現協議
text.delegate = self;
// 把 textfield 加到視圖中
[self.window addSubview:text];
// 在最右側加圖片(左側類似)
UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
text.rightView = image;
text.rightViewMode = UITextFieldViewModeAlways;
類別需採用 UITextFieldDelegate 協議,並把 text 的代理設為 self:
text.delegate = self;
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[text resignFirstResponder]; // 在哪調用就能把該 receiver 對應的鍵盤收起
return YES;
}
除了風格選項,你還可以透過重寫以下方法自訂 UITextField 各部件的邊界與繪製行為(皆回傳 CGRect):
– textRectForBounds: // 重置文字區域
– drawTextInRect: // 改變繪製文字屬性
– placeholderRectForBounds: // 重置佔位符區域
– drawPlaceholderInRect: // 改變繪製佔位符屬性
– borderRectForBounds: // 重置邊緣區域
– editingRectForBounds: // 重置編輯區域
– clearButtonRectForBounds: // 重置 clearButton 位置
– leftViewRectForBounds:
– rightViewRectForBounds:
// 是否允許開始編輯
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
// 開始編輯時觸發,文本字段將成為 first responder
- (void)textFieldDidBeginEditing:(UITextField *)textField{
}
// 是否允許結束編輯;返回 NO 可阻止 textField 消失(如即時消息需保持活躍)
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
return NO;
}
// 內容即將改變時調用,可用於加入撤銷或審計日誌;返回 NO 可阻止改變
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return YES;
}
// 是否允許根據用戶請求清除內容
- (BOOL)textFieldShouldClear:(UITextField *)textField{
return YES;
}
// 是否允許在按下回車鍵時結束編輯
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
UITextField 派生自 UIControl,因此可使用其通知系統。此外還有幾個 UITextField 特有事件:
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification
由於使用鍵盤輸入,以下事件發生時也會發送通知:
UIKeyboardWillShowNotification // 鍵盤顯示之前
UIKeyboardDidShowNotification // 鍵盤顯示之後
UIKeyboardWillHideNotification // 鍵盤隱藏之前
UIKeyboardDidHideNotification // 鍵盤隱藏之後
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
BOOL canChange = [string isEqualToString:filtered];
return canChange;
}
其中 NUMBERS 是一個可在檔案頂部定義的宏:
#define NUMBERS @"0123456789\n"
(代表可輸入數字與換行;注意這個 \n,若不寫,Done 鍵將不會觸發,用在 SearchBar 中也無法觸發 Search 事件。)若要限制只能輸入英文與數字:
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@"\n"]) { // 按回車可以改變
return YES;
}
NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (self.myTextField == textField) {
if ([toBeString length] > 20) {
textField.text = [toBeString substringToIndex:20];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"超過最大字數不能輸入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}