1

我想在 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
4

3 回答 3

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;
}

您可能需要考虑在此处检查长手势识别器,这远非 hack。

于 2013-08-20T21:24:10.043 回答
2

查看其中的方法,UITextInput因为这是控制选择的地方。您可以充当inputDelegate查找时间selectionWillChange:并覆盖selectedTextRange以控制选择和插入符号的行为。

文档:http: //developer.apple.com/library/ios/documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intfp/UITextInput

于 2013-06-29T08:43:59.653 回答
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
        }
    }

}
于 2014-07-24T09:04:36.063 回答