Search code examples
iosswiftuitextfielduitapgesturerecognizer

How to add LongPressGestureRecognizer into disabled TextField


I have TextField that isEnabled = false,

now I am trying to add UILongPressGestureRecognizer

inside UITableViewCell :

override func awakeFromNib() {
    super.awakeFromNib()
    let tap = UILongPressGestureRecognizer(target: userNameTextField, action: #selector(userNamelongPressAction))
    self.addGestureRecognizer(tap)
}

but I get crash

'NSInvalidArgumentException', reason: '-[UITextField userNamelongPressAction]: unrecognized selector sent to instance

what can I do? thanks


Solution

  • Its a common mistake, you are adding the target wrongly to UITextField, instead you must set target to where you implement the method userNamelongPressAction

    this code is assuming that you have implemented userNamelongPressAction method in this class context

    override func awakeFromNib() {
        super.awakeFromNib()
        let tap = UILongPressGestureRecognizer(target: self, action: #selector(userNamelongPressAction))
        self.addGestureRecognizer(tap)
    }
    

    Hope this help