Search code examples
iosobjective-cuitextviewdisabled-input

Disable text selection in UITextView


I want to disable text editing in UITextView, only cursor should stay. I already disabled keyboard, cut-copy-paste menu and zoom edit mode. But there still one problem - if I double tapping on TextView it's selects whole word. And one more thing, how can I let cursor select any place, not only end or start of word?

I did screenshots, which better describes my problem, but cant post it because of reputation. So I hope, that you will understand what exactly I mean.

Subclass of 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

Solution

  • Here comes Swift working example

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