//省的下面打 先定义好来安全
#define kWidthOfScreen ([UIScreen mainScreen].bounds.size.width)less
#define kHeightOfScreen ([UIScreen mainScreen].bounds.size.height)ide
@interface ViewController ()<UITextFieldDelegate>//遵照协议.net
{代理
UITextField *tf ;server
}图片
@endrem
- (void)viewDidLoad {get
[super viewDidLoad];string
// 建立方式
tf = [[UITextField alloc]init];
// 设置背景颜色
// tf.backgroundColor = [UIColor redColor];
// tf.background(背景图片)
// 添加到view上
[self.view addSubview:tf];
// 设置frame
tf.frame = CGRectMake(10, kHeightOfScreen - 30, kWidthOfScreen - 20, 30);
// typedef NS_ENUM(NSInteger, UITextBorderStyle) {
// UITextBorderStyleNone,
// UITextBorderStyleLine,
// UITextBorderStyleBezel,
// UITextBorderStyleRoundedRect
// };
//
// typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
// UITextFieldViewModeNever,
// UITextFieldViewModeWhileEditing,
// UITextFieldViewModeUnlessEditing,
// UITextFieldViewModeAlways
// };
tf.borderStyle = UITextBorderStyleRoundedRect;
tf.clearButtonMode = UITextFieldViewModeAlways;
// tf.clearsOnBeginEditing = YES;
// 设置第一响应者
[tf becomeFirstResponder];
// 取消第一响应者
// [tf resignFirstResponder];
tf.placeholder = @"placeholder";
// tf.attributedPlaceholder
// 设置代理为self
tf.delegate = self;
// 设置键盘样式 (枚举)
tf.keyboardType = UIKeyboardTypeDefault;
// 设置键盘右下角的文字(枚举)
tf.returnKeyType = UIReturnKeySend;
// 设置安全输入
// tf.secureTextEntry = YES;
// 设置左右两边的view
// tf.leftView
// tf.leftViewMode
// tf.rightView
// tf.rightViewMode
// 添加通知 监听键盘 show-hide
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(show:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hide:) name:UIKeyboardDidHideNotification object:nil];
}
-(void)dealloc{
// 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
-(void)show:(NSNotification*)noti{
CGRect keyboardFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect tfFrame = tf.frame;
tfFrame.origin.y -= keyboardFrame.size.height;
tf.frame = tfFrame;
}
-(void)hide:(NSNotification*)noti{
tf.frame = CGRectMake(10, kHeightOfScreen - 30, kWidthOfScreen - 20, 30);
}
//下面是经常使用的代理方法
-(BOOL)textFieldShouldClear:(UITextField *)textField{
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField endEditing:YES];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(@"end");
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
NSLog(@"begin");
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"%@",string);
return YES;
}
附模拟器键盘弹不起的解决方案
将下图中第三个没有勾上的打勾