UITextView disabling text selection

2020-02-02 08:04发布

I'm having a hard time getting the UITextView to disable the selecting of the text.

I've tried:

canCancelContentTouches = YES;

I've tried subclassing and overwriting:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender   

(But that gets called only After the selection)

- (BOOL)touchesShouldCancelInContentView:(UIView *)view;  

(I don't see that getting fired at all)

- (BOOL)touchesShouldBegin:(NSSet *)touches
                 withEvent:(UIEvent *)event
             inContentView:(UIView *)view; 

(I don't see that getting fired either)

What am I missing?

11条回答
狗以群分
2楼-- · 2020-02-02 08:43

I've found that calling

[textView setUserInteractionEnabled:NO];

works quite well.

查看更多
地球回转人心会变
3楼-- · 2020-02-02 08:43

To do this first subclass the UITextView

and in the implementation do the following

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
    self.selectable = NO;
}

- (void)touchesCancelled:(nullable NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
        self.selectable = YES;
 }

this should work fine,

查看更多
Anthone
4楼-- · 2020-02-02 08:43

Swift 4, Xcode 10

This solution will

  • disable highlighting
  • enable tapping links
  • allow scrolling

Make sure you set the delegate to YourViewController

yourTextView.delegate = yourViewControllerInstance

Then

extension YourViewController: UITextViewDelegate {

    func textViewDidChangeSelection(_ textView: UITextView) {
        view.endEditing(true)
    }

}
查看更多
虎瘦雄心在
5楼-- · 2020-02-02 08:46

Did you try setting userInteractionEnabled to NO for your UITextView? But you'd lose scrolling too.

If you need scrolling, which is probably why you used a UITextView and not a UILabel, then you need to do more work. You'll probably have to override canPerformAction:withSender: to return NO for actions that you don't want to allow:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    switch (action) {
        case @selector(paste:):
        case @selector(copy:):
        case @selector(cut:):
        case @selector(cut:):
        case @selector(select:):
        case @selector(selectAll:):
        return NO;
    }
    return [super canPerformAction:action withSender:sender];
}

For more, UIResponderStandardEditActions .

查看更多
对你真心纯属浪费
6楼-- · 2020-02-02 08:51

For swift, there is a property called "isSelectable" and its by default assign to true

you can use it as follow:

textView.isSelectable = false
查看更多
登录 后发表回答