- (void)viewDidLoad {
[super viewDidLoad];
[self setupButtomView];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWillShow:) name:@"UIKeyboardWillShowNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWillHidden:) name:@"UIKeyboardWillHideNotification" object:nil];
}
//键盘即将出现的时候
- (void)keyboardWillShow:(NSNotification *)sender{
CGRect keyboardRect = [(sender.userInfo[UIKeyboardFrameBeginUserInfoKey]) CGRectValue];
//改变bttomView的y值,防止被键盘遮住
CGRect bottomViewRect = self.bottomView.frame;
bottomViewRect.origin.y = self.view.frame.size.height - keyboardRect.size.height - bottomViewRect.size.height;
self.bottomView.frame = bottomViewRect;
}
//键盘即将消失的时候
- (void)keyboardWillHidden:(NSNotification *)sender{
CGRect bottomViewRect = self.bottomView.frame;
bottomViewRect.origin.y = self.view.frame.size.height - 65;
self.bottomView.frame = bottomViewRect;
}
//键盘的布局
- (void)setupButtomView{
self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height - 65, CGRectGetWidth(self.view.frame),65)];
self.bottomView.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.bottomView];
//添加textfield
self.commentTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 100,45)];
self.commentTextField.backgroundColor = [UIColor whiteColor];
self.commentTextField.layer.cornerRadius = 10;
[self.bottomView addSubview:self.commentTextField];
//textField遵循协议
self.commentTextField.delegate = self;
//添加button
self.commentButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.commentButton.frame = CGRectMake(self.view.frame.size.width -80, 10, 70, 45);
self.commentButton.backgroundColor = [UIColor whiteColor];
self.commentButton.layer.cornerRadius = 10;
[self.commentButton setTitle:@"发送" forState:UIControlStateNormal];
[self.commentButton addTarget:selfaction:@selector(commentButtonAction:)forControlEvents:UIControlEventTouchUpInside];
[self.bottomView addSubview:self.commentButton];
//关闭button的用户交互
self.commentButton.userInteractionEnabled = NO;
}
//发送按钮的回调方法
- (void)commentButtonAction:(UIButton *)sender{
//取消第一响应者
[self.commentTextField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//文本框内容发生变化
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//当文本框只有一个字符的时候,我们需要判定该字符是添加的还是需要删除的。如果是添加,需要打开用户交互,如果是删除,需要关闭用户交互
if (string.length){//添加字符串,打开用户交互
self.commentButton.userInteractionEnabled = YES;
}
else{
if (textField.text.length <= 1) {
self.commentButton.userInteractionEnabled = NO;
}
}
return YES;
}