swiftuitextfielduser-interaction

Enable selecting text without user interaction enabled


I have a text field with the phone number in it. It should not be edited, but the user should have an ability to select it by long pressing on the phone. When he long presses text should get selected, not just copied to the clipboard. So far I only got it to work with isUserInteractionEnabled == true but I need to still have it false. Any suggestion on how I could do this? My code now:

func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
    self.cell?.textField.isUserInteractionEnabled = true
    self.cell?.textField.becomeFirstResponder()
    self.cell?.textField.selectedTextRange = self.cell?.textField.textRange(from: (self.cell?.textField.beginningOfDocument)!, to: (self.cell?.textField.endOfDocument)!)
    //self.cell?.textField.isUserInteractionEnabled = false
}

Solution

  • For your purposes, UITextField is not a suitable choice. As the documentation states, UITextField is (emphasis added by me):

    An object that displays an editable text area in your interface.

    Hence, you cannot set a UITextField to be non-editable. If you want to display text on the UI, which shouldn't be editable, use a UILabel or UITextView.

    You can set the UITextView's isEditable property to false and it will still be selectable as long as isSelectable is set to true.

    A UILabel displays read only text, so you don't even need to take care of disabling editing when using it.