ghosting999
ghosting999

Reputation: 101

How can I add a UITapGestureRecognizer to a UILabel inside a table view cell? Swift2

I am using a custom table view cell. This cell has a label with outlet called chatNameLabel. Adding a UILongPressGestureRecognizer to this label never fires the associated event.

I'm guessing that the problem is that the UILabel is in a TableView and that the table/cell view is intercepting the taps. Can I do something about this?

All I want to do is perform some custom action when a UILabel is long pressed!

I believe this was answered in Objective-C however I am not familiar with the language at all and new to swift.

Here's the code I'm using:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let sessions = self.chatSessions where sessions.indices.contains(indexPath.row) {
        let session = sessions[indexPath.row]



        if session.sessionId == nil {
            //DO A THING
        }
        // existing session id (existing chat)
        else {
            let cell = tableView.dequeueReusableCellWithIdentifier("ChatListCell", forIndexPath: indexPath) as! ChatListTableViewCell
            cell.tag = indexPath.row

            if(session.unreadChats) {
                cell.indicatorImageView.tintColor = AppStyles.sharedInstance.indicatorActive
            }
            else{
                cell.indicatorImageView.hidden = true
            }
            //Want to do gesture on this label below cell.chatNameLabel
            cell.chatNameLabel.text = session.chatName

... Some more code not needed for question below this

Upvotes: 0

Views: 813

Answers (1)

Haligen
Haligen

Reputation: 231

Your class needs implement UIGestureRecognizerDelegate , then the below code should work.

myLabel.userInteractionEnabled = true
let tap: UILongPressGestureRecognizer = UILongPressGestureRecognizer(
target: self, action: #selector(tappedTheLabel))
tap.minimumPressDuration = 0.5
tap.delaysTouchesBegan = true
myLabel.addGestureRecognizer(tap)
tap.delegate = self
}

func tappedTheLabel(sender: UITapGestureRecognizer)
{
print("label hit \(sender)")
}

Upvotes: 2

Related Questions