在 iOS 表單與登錄頁面中,UITextField 是最常見的單行文本輸入控件之一。它適用於用戶名、密碼、搜尋關鍵字等只需要輸入一行文字的场景。
首先在視圖控制器中宣告 UITextField 屬性,並遵循 UITextFieldDelegate 協議。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *textField;
@end
在 viewDidLoad 中建立 text field,並設定位置、字體、邊框、鍵盤類型、提示文字與代理。
- (void)viewDidLoad {
[super viewDidLoad];
self.textField = [[UITextField alloc] init];
self.textField.frame = CGRectMake(100, 100, 180, 40);
self.textField.font = [UIFont systemFontOfSize:15];
self.textField.textColor = [UIColor blackColor];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.keyboardType = UIKeyboardTypeNumberPad;
self.textField.placeholder = @"請輸入用戶名";
self.textField.secureTextEntry = YES;
self.textField.delegate = self;
[self.view addSubview:self.textField];
}
borderStyle:控制邊框樣式,例如圓角、線框或無邊框。keyboardType:控制鍵盤類型,例如數字鍵盤、電話鍵盤或預設鍵盤。placeholder:當輸入框沒有內容時顯示的提示文字。secureTextEntry:設定為 YES 時,輸入內容會以圓點顯示,常用於密碼輸入。透過代理可以監聽開始編輯、結束編輯,以及是否允許開始或結束編輯。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(@"開始編輯");
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSLog(@"結束編輯");
self.textField.text = @"";
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
return YES;
}
如果希望點擊畫面空白處時收起鍵盤,可以在接收到觸摸事件時讓 text field 結束第一響應者狀態。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.textField resignFirstResponder];
}
透過這些基本設定,就可以完成一個具備輸入、提示、密碼顯示與鍵盤控制能力的單行文本輸入框。