UItextField通常用於外部數據輸入,以實現人機交互。下面以一個簡單的登陸界面來講解UItextField的詳細使用。
//用來顯示“用戶名”的label
UILabel* label1 = [[UILabelalloc] initWithFrame:CGRectMake(15, 65, 70, 30)];
label1.backgroundColor = [UIColorclearColor];
label1.font = [UIFontfontWithName:@"Helvetica-Bold"size:18];
label1.text = @"用戶名";
label1.textColor = [UIColorwhiteColor];
[view1 addSubview:label1];
[label1 release];
UITextField * accountField = [[UITextField alloc] initWithFrame:CGRectMake(85.0f, 60.0f, 190.0f, 40.0f)];
[accountField setBorderStyle:UITextBorderStyleRoundedRect]; //外框類型
accountField.placeholder = @"用戶名"; //默認顯示的字
accountField.secureTextEntry = NO; //是否以密碼形式顯示
accountField.autocorrectionType = UITextAutocorrectionTypeNo;//設置是否啟動自動提醒更正功能
accountField.autocapitalizationType = UITextAutocapitalizationTypeNone;
accountField.returnKeyType = UIReturnKeyDone; //鍵盤返回類型
accountField.clearButtonMode = UITextFieldViewModeWhileEditing; //編輯時會出現個修改X
accountField.delegate = self;
accountField.keyboardType = UIKeyboardTypeDefault;//鍵盤顯示類型
accountField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; //設置居中輸入
accountField.scrollEnabled = YES;//是否可以拖動
accountField.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自適應高度
//用來顯示“密碼”的label
UILabel* label2 = [[UILabelalloc] initWithFrame:CGRectMake(15, 120, 70, 30)];
label2.backgroundColor = [UIColorclearColor];
label2.font = [UIFontfontWithName:@"Helvetica-Bold"size:18];
label2.text = @"密碼";
label2.textColor = [UIColorwhiteColor];
[view1 addSubview:label2];
[label2 release];
UITextField* passwdField = [[UITextField alloc] initWithFrame:CGRectMake(85.0f, 115.0f, 190.0f, 40.0f)];
[passwdFieldsetBorderStyle:UITextBorderStyleRoundedRect]; //外框類型
//passwdField.placeholder = @"密碼"; //默認顯示的字
passwdField.secureTextEntry = YES; //密碼類型
passwdField.autocorrectionType = UITextAutocorrectionTypeNo;
passwdField.autocapitalizationType = UITextAutocapitalizationTypeNone;
passwdField.returnKeyType = UIReturnKeyDone;
passwdField.clearButtonMode = UITextFieldViewModeWhileEditing; //編輯時會出現個修改X
passwdField.delegate = self;
// passwdField.keyboardAppearance = UIKeyboardAppearanceDefault;
passwdField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
passwdField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
委托方法
-(void)textFieldDidBeginEditing:(UITextField *)textField;
//當開始點擊textField會調用的方法
-(void)textFieldDidEndEditing:(UITextField *)textField;
//當textField編輯結束時調用的方法
//按下Done按鈕的調用方法,我們讓鍵盤消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}