如何让UITextView光标一直处于焦点状态?
正常情况下来说,UITextView只有在becomeFirstResponder状态时,才会处于焦点状态。这是光标才会出现,若是resignFirstResponder后,则会收缩键盘,光标消失,那么该如何将在resignFirstResponder没有键盘的状态下,还能保持光标的存在呢?
首先了解到UITextView有个自定义输入视图
// set while first responder, will not take effect until reloadInputViews is called. @property (nullable, readwrite, strong) UIView *inputView;
inputView可以自定义一个输入视图,也就是键盘的位置。
因此在正常进行输入时,我们点击调用正常的系统键盘,当需要退出键盘,但同时要保留焦点时,我们则将自定义键盘的inputView置空。
- (void)showKeyBoard:(BOOL)show { [self.textToolsView.content_textview becomeFirstResponder]; if (show) { if (!self.textToolsView.content_textview.inputView) { return; } [self.textToolsView.content_textview resignFirstResponder]; self.textToolsView.content_textview.inputView = nil; } else { if (self.textToolsView.content_textview.inputView) { return; } [self.textToolsView.content_textview resignFirstResponder]; self.textToolsView.content_textview.inputView = [UIView new]; } [self.textToolsView.content_textview becomeFirstResponder]; }
这样便能达到我们的效果,但是也有一个小小的问题,就是在键盘消失后,虽然光标还在,这是点击TextView是无法调用起系统键盘的,因此需要给UITextView添加监听!但是UITextView开放的API中,并没有相关事件,那么该如何处理呢?
for (UIGestureRecognizer *gesture in _textToolsView.content_textview.gestureRecognizers) { if ( [NSStringFromClass(gesture.class) isEqualToString:@"UIScrollViewDelayedTouchesBeganGestureRecognizer"]) { gesture.delegate = self; } }
看到以上代码相信你该明白了,我们将UITextView的UIScrollViewDelayedTouchesBeganGestureRecognizer点击手势代理到本类中,因此便能够监听到UITextView的点击事件,并进行相关操作.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ if ([NSStringFromClass(otherGestureRecognizer.class) isEqualToString:@"UIVariableDelayLoupeGesture"]) { return NO; } // [self showKeyBoard:YES]; return YES; }