Search code examples
iosswiftuitextviewuitextviewdelegate

UITextView - Begin Editing With All Text Selected In UITableViewCell()


I have a tableView with an object TaskCell which is a subclass of UITableViewCell

The textView is in the TaskCell and everything works fine except I can not get this line of code to select all text in the text view so the user can immediately overwrite the text if they so desire. Just as if you were to tap "select all" after holding onto the tap of the text.

textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.endOfDocument)

_

// All code relating to textView
class TaskCell: UITableViewCell {

  @IBOutlet weak var textView: UITextView! { didSet { initTextView() } }

  fileprivate func initTextView() {
    textView.delegate = self
  }
}

extension TaskCell: UITextViewDelegate {
  func textViewDidBeginEditing(_ textView: UITextView) {
    textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.endOfDocument)
  }
}


// class ListViewController: ViewController, UITableViewDataSource, UITableViewDelegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TaskCell

    return cell
}

Solution

  • You have two options :

     [yourtextView selectAll:nil];        //highlights text
     [yourtextView selectAll:self];       //highlights text and shows menu(cut copy paste)
    

    in your case this will solve it :

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

    Swift 3.0

    func textViewDidBeginEditing(_ textView: UITextView) {
        DispatchQueue.main.async {
            textView.selectAll(nil)
        }
    }
    

    enter image description here