UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(60, 180, 200, 35)];
tf.tag = 101;
tf.delegate = self; // 设置代理
tf.textColor = [UIColor redColor];
//提示用户输入的内容文本
tf.placeholder = @"用来提示用户";
//自适应调整字体大小,默认为NO
tf.adjustsFontSizeToFitWidth = YES;
//用户编辑时是否Clean内容,默认是NO
tf.clearsOnBeginEditing = YES;
//清除按钮的模式,默认不出现
tf.clearButtonMode = UITextFieldViewModeWhileEditing;
// tf.background = [UIImage imageNamed:@"navigation"];
tf.borderStyle = UITextBorderStyleRoundedRect;//显示和android一样的框
[tf becomeFirstResponder];//响应键盘事件
// 自定义clear按钮
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
view.backgroundColor = [UIColor yellowColor];
tf.rightView = view;
[view release];
tf.rightViewMode = UITextFieldViewModeUnlessEditing;
// 自定义系统键盘
UIView *csView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
csView.backgroundColor = [UIColor yellowColor];
tf.inputView = csView;
[csView release];
//系统键盘和自定义键盘共存
tf.inputAccessoryView = csView1;
//是否安全输入,比如用户名,密码
tf.secureTextEntry = YES;
//修改键盘类型
tf.keyboardType = UIKeyboardTypeNumberPad;
//修改返回类型
tf.returnKeyType = UIReturnKeyDone;
//自动大写类型
tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
UITextField *tf = (UITextField *)[self.window viewWithTag:101];
// 将键盘移除
[tf resignFirstResponder];
代理方法:
#pragma mark - TextField Delegate
//将要开始输入时调用,就是键盘要显示时调用
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
NSLog(@"textFieldShouldBeginEditing");
return YES; // [textField becomeFirstResponder];
}
//键盘已经显示,做好编辑准备时调用
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"textFieldDidBeginEditing");
}
//将要输入结束时调用,就是键盘将要离开时调用
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"textFieldShouldEndEditing");
return YES; // [tf resignFirstResponder];
}
//键盘已经离开,结束编辑时调用,
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSLog(@"textFieldDidEndEditing : %@", textField.text);
}
//文本改变监听
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"shouldChangeCharactersInRange : %@", string);
return YES;
}
//清除文字按钮点击事件
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSLog(@"textFieldShouldClear");
return YES;
}
//键盘上的return按钮事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//隐藏输入键盘
[textField resignFirstResponder];
return YES;
}