一.输入结束时调用
#pragma mark--UITextFieldDelegate--输入完成时调用- (void)textFieldDidEndEditing:(UITextField *)textField{ if(![textField.text isEqualToString:@""]){ //处理事件 } }#pragma mark--UITextFieldDelegate---键盘回调- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; }
二.输入时改变
1.添加事件
[_textField addTarget:self action:@selector(textFieldDidChangeValue:) forControlEvents:UIControlEventEditingChanged];- (void)textFieldDidChangeValue:(id)sender{ if(![_textField.text isEqualToString:@""]){ //处理事件 }}
2.添加通知监听
//添加通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:_textField];- (void)textFieldDidChangeValue:(NSNotification *)notification{ UITextField *textField = (UITextField *)[notification object]; //处理事件}//移除注册的通知-(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
三.键盘遮挡问题
#define Main_Screen_Height [[UIScreen mainScreen] bounds].size.height#define Main_Screen_Width [[UIScreen mainScreen] bounds].size.width//键盘通知- (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillChangeFrameNotification object:nil];}//键盘弹出 处理遮挡问题- (void)keyboardWillShown: (NSNotification *)notify { NSDictionary *dic = notify.userInfo;// CGFloat duration = [[dic objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; NSValue *value = [dic objectForKey:UIKeyboardFrameEndUserInfoKey]; CGSize size = [value CGRectValue].size;//获取键盘高度 CGFloat keyBoardHeight = size.height; CGRect frame = _numField.frame; int offset = frame.origin.y + 300 - (Main_Screen_Height - keyBoardHeight); [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:0.3f]; //将视图y坐标向上移动offset个单位,以使下面有地方显示键盘 if(offset > 0){ self.view.frame = CGRectMake(0.0f, -offset, Main_Screen_Width,Main_Screen_Height); self.view.backgroundColor = Sec_Search_Color; } [UIView commitAnimations]; }#pragma mark--UITextFieldDelegate编辑完成,视图恢复原状-(void)textFieldDidEndEditing:(UITextField *)textField{ self.view.frame =CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height);}
四、修改textField.placeholder的字体颜色和大小
[_searchBar.textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"]; [_searchBar.textField setValue:[UIFont fontWithName:@"PingFangSC-Regular" size:14] forKeyPath:@"_placeholderLabel.font"];