//省的下面打 先定義好來安全
#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;
}
附模擬器鍵盤彈不起的解決方案
將下圖中第三個沒有勾上的打勾