UITextView selectAll method not working as expected

前端 未结 3 1616
野趣味
野趣味 2021-02-20 05:01

I\'m creating an iOS 8 app with Xcode 6.0.1 for my iPhone 5 (which has iOS 8.0.2 on it). I want to make it so that when a user clicks on my UITextView, all the text

相关标签:
3条回答
  • 2021-02-20 05:21

    This solution works too and does not require subclassing UITextView, just put this function on your delegate:

    OBJECTIVE C -

    - (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
      dispatch_async(dispatch_get_main_queue(), ^{
        [textView selectAll:nil];
      });
      return YES;
    }
    

    SWIFT 3 -

    func textViewDidBeginEditing(_ textView: UITextView) {
        DispatchQueue.main.async {
            textView.selectAll(nil)
        }
    }
    
    0 讨论(0)
  • 2021-02-20 05:29

    @brentvatne 's solution worked for me. Posting the Swift syntax so people can copy and paste in the future.

    func textViewShouldBeginEditing(textView: UITextView) -> Bool {
        dispatch_async(dispatch_get_main_queue()) {
            textView.selectAll(nil)
        }
        return true
    }
    
    0 讨论(0)
  • 2021-02-20 05:33

    The best solution I've found for this issue so far is to create a custom UITextView (i.e. create a new class that extends UITextView) and then implement the selectAll method like this:

    - (void)selectAll:(id)sender {
        [super selectAll:sender];
        UITextRange *selectionRange = [self textRangeFromPosition:self.beginningOfDocument toPosition:self.endOfDocument];
        [self performSelector:@selector(setSelectedTextRange:) withObject:selectionRange afterDelay:0.0];
    }
    

    Then when you use a text view, set its type to your custom text view type (in your code and in the storyboard). Now you can successfully call the selectAll method whenever you need to. I suppose this should work with UITextField too, but I haven't tried it yet.

    0 讨论(0)
提交回复
热议问题