如何将TapGestureRecognizer添加到单元格内的标签?

时间:2016-04-27 20:22:01

标签: ios swift

我将UITableViewCell子类化。我尝试添加手势识别器,但点击它时没有任何反应。

class MessagesTableViewCell: UITableViewCell {


    @IBOutlet weak var nameLabel: UILabel!

    var profileTap:UITapGestureRecognizer?


    func render(){
        if profileTap == nil {
            print("Here") //prints.
            profileTap = UITapGestureRecognizer()
            profileTap?.addTarget(self, action: #selector(MessagesTableViewCell.profileTapped(_:)))
            nameLabel.addGestureRecognizer(profileTap!)
        }
    }


    func profileTapped(sender: UITapGestureRecognizer!){
        print("tapped")
    }
}

我不需要我的细胞可供选择。我只需要标签。

2 个答案:

答案 0 :(得分:0)

确保标签的userInteractionEnabled属性为true,默认情况下UILabel不是用户交互。

label.userInteractionEnabled = true

或者,使用UIButton。

答案 1 :(得分:0)

你真的需要一个手势识别器吗?更好的方法是使用清晰的UIButton绑定简单块:

var closeHandler:(()->())?


@IBAction func profileTapped(sender: UIButton!){
    if let handler = closeHandler { handler() }
}

在你的cellForRow:方法:

    cell.closeHandler = {
            //do your stuff
        }
相关问题