標籤:http java color os 檔案 io
UITextField展示的是一些可編輯的內容,並且與使用者有一些互動。比如當你在虛擬鍵盤上按下return鍵時,一般會關聯到鍵盤隱藏事件上。UITextField的一些狀態大多在UITextFieldDelegate協議中有相應的方法。
UITextField的初始化及一些屬性
//姓名輸入欄位UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, 200, 44)];nameField.tag = 100;nameField.delegate = self; //預設文字 nameField.placeholder = @"name"; nameField.font = [UIFont systemFontOfSize:16.0f]; nameField.textColor = [UIColor blackColor]; //輸入框的背景圖片(還可以選擇設定背景顏色) nameField.background = [UIImage imageNamed:@"textFieldBackgroundImage"]; //nameField.backgroundColor = [UIColor lightGrayColor]; //清除按鈕 nameField.clearButtonMode = UITextFieldViewModeAlways; //鍵盤類型 nameField.keyboardType = UIKeyboardTypeDefault; [self.view addSubview:nameField]; 電話輸入欄位 UITextField *phoneField = [[UITextField alloc] initWithFrame:CGRectMake(30, nameField.frame.origin.y + nameField.bounds.size.height+10, 200, 44)]; phoneField.tag = 101; phoneField.delegate = self; phoneField.placeholder = @"phone"; phoneField.keyboardType = UIKeyboardTypeDecimalPad; phoneField.clearButtonMode = UITextFieldViewModeAlways; [self.view addSubview:phoneField]; //郵箱輸入欄位 UITextField *emailField = [[UITextField alloc] initWithFrame:CGRectMake(30, phoneField.frame.origin.y + phoneField.bounds.size.height + 10, 200, 44)]; emailField.tag = 102; emailField.delegate = self; emailField.placeholder = @"email"; emailField.keyboardType = UIKeyboardTypeEmailAddress; emailField.clearButtonMode = UITextFieldViewModeAlways; [self.view addSubview:emailField];
UITextField隱藏鍵盤
1.點擊鍵盤的return來隱藏鍵盤
這個方法需要在相應的.h檔案檔案中實現UITextFieldDelegate協議。並在.m檔案中添加如下方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}
2.點擊介面空白處來隱藏鍵盤
這個方法的實現主要是給當前的view增加點擊事件,並未點擊事件增加相應的處理方法,此處是為了隱藏鍵盤,所以我們可以在點擊事件對應的方法中讓UITextField放棄第一響應者。
- (void)dismissKeyboard{ NSArray *subViews = [self.view subviews]; for (id inputText in subViews) { if ([inputText isKindOfClass:[UITextField class]]) { if ([inputText isFirstResponder]) { [inputText resignFirstResponder]; } } }}
為當前的view增加點擊事件
UITapGestureRecognizer *dismissKeyboardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];[self.view addGestureRecognizer: dismissKeyboardTap];
UITextField--為內容增加校正
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ switch (textField.tag) { case 100://name { NSLog(@"this is nameField"); //添加校正name的代碼 break; } case 101://phone { NSLog(@"this is phoneField"); //添加校正phone的代碼 break; } case 102://email { NSLog(@"this is emailField"); //添加校正email的代碼 break; } default: break; } return YES;}