我想在UITextView中禁用文本编辑,只留下光标。我已经禁用了键盘,剪切复制粘贴菜单和缩放编辑模式。但是还有一个问题 - 如果我双击TextView它会选择整个单词。还有一件事,我怎样才能让光标选择任何地方,而不仅仅是结束或开始?
我做了截图,更好地描述了我的问题,但因为声誉而无法发布。所以我希望你明白我的意思。
UITextView的子类:
#import "UIUneditableTextView.h"
@implementation UIUneditableTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
UIMenuController *menuController = [UIMenuController sharedMenuController];
if (menuController) {
[UIMenuController sharedMenuController].menuVisible = NO;
}
return NO;
}
-(void)addGestureRecognizerForLongPress:(UIGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
gestureRecognizer.enabled = NO;
}
[super addGestureRecognizer:gestureRecognizer];
return;
}
@end
答案 0 :(得分:3)
由于你已经在重载文本视图,请实现gestureRecognizerShouldBegin:我做了这样的实现。
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
// Check for gestures to prevent
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
// Check for double tap
if (((UITapGestureRecognizer *)gestureRecognizer).numberOfTapsRequired == 2) {
// Prevent the double tap
return NO;
}
}
// Always anything that makes it here
return YES;
}
您可能需要考虑在这里检查长手势识别器,这不是一个黑客攻击。
答案 1 :(得分:2)
查看UITextInput
中的方法,因为这是控制选择的地方。您可以充当inputDelegate
以查找何时selectionWillChange:
并覆盖selectedTextRange
来控制选择和插入符号。
答案 2 :(得分:1)
这是Swift的工作示例
class TextView: UITextView {
override func canPerformAction(action: Selector, withSender sender: AnyObject!) -> Bool {
return false
}
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer!) -> Bool {
if gestureRecognizer.isKindOfClass(UITapGestureRecognizer) && ((gestureRecognizer as UITapGestureRecognizer).numberOfTapsRequired == 1) {
let touchPoint = gestureRecognizer.locationOfTouch(0, inView: self)
let cursorPosition = closestPositionToPoint(touchPoint)
selectedTextRange = textRangeFromPosition(cursorPosition, toPosition: cursorPosition)
return true
}
else {
return false
}
}
}