关于点击UIButton弹出键盘,并且键盘的上方还需添加UITextField或者UITextView的解决方法

时间:2021-11-14 00:34:38

最近在做一个项目的时候,有这样一个需求,点击UIButton弹出键盘,键盘的上方还需添加一个输入框(UITextField/UITextView,开始的想法是直接设置输入框的

inputAccessoryView,设置后发现键盘根本就没显示出来.经过无数次的修改与查找资料之后,终于大功告成。废话不多说了,先上代码。


//创建输入框视图

- (void)createCommentsView {
if (!commentsView) {

commentsView = [[UIView alloc] initWithFrame:CGRectMake(0.0, SCREEN_HEIGHT - TAB_BAR_HEIGHT - 40.0, SCREEN_WIDTH, 40.0)];
commentsView.backgroundColor = [UIColor whiteColor];

commentText = [[UITextView alloc] initWithFrame:CGRectInset(commentsView.bounds, 5.0, 5.0)];
commentText.layer.borderColor = [COLORRGB(212.0, 212.0, 212.0) CGColor];
commentText.layer.borderWidth = 1.0;
commentText.layer.cornerRadius = 2.0;
commentText.layer.masksToBounds = YES;

commentText.inputAccessoryView = commentsView;
commentText.backgroundColor = [UIColor clearColor];
commentText.returnKeyType = UIReturnKeySend;
commentText.delegate = self;
commentText.font = [UIFont systemFontOfSize:15.0];
[commentsView addSubview:commentText];
}
[self.view.window addSubview:commentsView];//添加到window上或者其他视图也行,只要在视图以外就好了
[commentText becomeFirstResponder];//让textView成为第一响应者(第一次)这次键盘并未显示出来,(个人觉得这里主要是将commentsView设置为commentText的inputAccessoryView,然后再给一次焦点就能成功显示)
}

- (void)showCommentText {
[self createCommentsView];

[commentText becomeFirstResponder];//再次让textView成为第一响应者(第二次)这次键盘才成功显示
}


//button的点击事件

- (void)handleClickComment:(UIButton *) sender {
//这里是为了防止连续点击
sender.userInteractionEnabled = NO;
[sender performSelector:@selector(setUserInteractionEnabled:) withObject:@YES afterDelay:1];
[self showCommentText];
}