|
UITextField展示的是一些可編輯的內(nèi)容,并且與用戶有一些交互。比如當(dāng)你在虛擬鍵盤上按下return鍵時,一般會關(guān)聯(lián)到鍵盤隱藏事件上。UITextField的一些狀態(tài)大多在UITextFieldDelegate協(xié)議中有相應(yīng)的方法。
UITextField的初始化及一些屬性
//姓名輸入域
UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, 200, 44)];
nameField.tag = 100;
nameField.delegate = self;
//默認(rèn)文字
nameField.placeholder = @"name";
nameField.font = [UIFont systemFontOfSize:16.0f];
nameField.textColor = [UIColor blackColor];
//輸入框的背景圖片(還可以選擇設(shè)置背景顏色)
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來隱藏鍵盤
這個方法需要在相應(yīng)的.h文件文件中實現(xiàn)UITextFieldDelegate協(xié)議。并在.m文件中添加如下方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
2.點擊界面空白處來隱藏鍵盤
這個方法的實現(xiàn)主要是給當(dāng)前的view增加點擊事件,并未點擊事件增加相應(yīng)的處理方法,此處是為了隱藏鍵盤,所以我們可以在點擊事件對應(yīng)的方法中讓UITextField放棄第一響應(yīng)者。
- (void)dismissKeyboard
{
NSArray *subViews = [self.view subviews];
for (id inputText in subViews) {
if ([inputText isKindOfClass:[UITextField class]]) {
if ([inputText isFirstResponder]) {
[inputText resignFirstResponder];
}
}
}
}
為當(dāng)前的view增加點擊事件
UITapGestureRecognizer *dismissKeyboardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer: dismissKeyboardTap];
UITextField--為內(nèi)容增加校驗
- (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;
}
|