Roman Roman - 3 months ago 12
iOS Question

Pass on Argument in #selector Swift 2.2

I have a method:

func followUnfollow(followIcon: UIImageView, channelId: String) {
let followUnfollow = followIcon
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.followIconTapped(_:)))
followUnfollow.userInteractionEnabled = true
followUnfollow.addGestureRecognizer(tapGestureRecognizer)
}


And also I have a method:

func followIconTapped(sender: UITapGestureRecognizer) {
...
}


And it's work all right. But I need to pass on
channelId
to
followIconTapped()
method.

I try this:

func followUnfollow(followIcon: UIImageView, channelId: String) {
...
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.followIconTapped(_:channelId)))
...
}


and then I try catch it:

func followIconTapped(sender: UITapGestureRecognizer, channelId: String) {
...
}


xCode say that
channelId
will never used. Why?
When I build project I haven't any issue. But app is crash if I tap on followIcon.

Please, can you give me advice how to pass on
channelId
to
followIconTapped()

Answer

creating a generic UITapGestureRecognizer instead use this:

class CustomTapGestureRecognizer: UITapGestureRecognizer {
    var channelId: String?
}

also use this:

override func viewDidLoad() {
    super.viewDidLoad()

    let gestureRecognizer = CustomTapGestureRecognizer(target: self, action: #selector(tapped(_:))
    gestureRecognizer.channelId = "Your string"
    view1.addGestureRecognizer(gestureRecognizer)
}

func tapped(gestureRecognizer: CustomTapGestureRecognizer) {
    if let channelId = gestureRecognizer.channelId {
        //print
    }
}
Comments