iosswiftuitextfielduitapgesturerecognizer

Adding Tap gesture recognizer to only text of UITextfield which is Uneditable


I am adding tap gesture recognizer in a table view like this.

# let tapGestureRecognizer = CustomTapGestureRecogniser(target: self, action: #selector(openMethod(tapGestureRecognizer:)))
                        tapGestureRecognizer.data = indexPath.row
                        cell.textField.isUserInteractionEnabled = true
                        cell.textField.addGestureRecognizer(tapGestureRecognizer)

But the whole textfield is clickable, I want this only on click of text


Solution

  • you can get it with this trick:

    textField.subviews[1].subviews.first?.subviews[3]
    
    

    you can see the view in "debug view hierarchy"(3D view) when your UIViewController is rendered:

    enter image description here

    and via right click on the view and choose the "Reveal in debug navigator" you can see the view hierarchy:

    enter image description here

    an see the hierarchy of the views:

    enter image description here

    and after that you can get it

    note that, in the update of iOS SDK it may change, you should check it if exist:

    if textField.subviews.count > 1,  
    textField.subviews[1].subviews.count > 0, 
    textField.subviews[1].subviews.first?.subviews.count > 3 {
       textField.subviews[1].subviews.first?.subviews[3]
    }
    
    

    you can see the hierarchy of the views with PO(print object command) like as:

    enter image description here

    enter image description here