向UILabel添加手势

时间:2019-06-21 19:48:20

标签: ios swift uilabel uigesturerecognizer

我正在尝试向我的UILabel添加轻击手势,但是在点击标签时无法使其弹出。我看了看其他所有人的情况,从我发现他们已经在一行中声明了标签,然后在视图中添加手势的确加载了。是否可以在我的标签声明中添加手势以使其保持整洁?

let apetureButton: UILabel = {
    let tapLabel = UITapGestureRecognizer(target: self, action: #selector(apetureSelect))
    let text = UILabel() 
    text.isUserInteractionEnabled = true
    text.addGestureRecognizer(tapLabel)
    text.text = "400"  
    return text
}()

@objc func apetureSelect(sender:UITapGestureRecognizer) {
     print("ApetureSelect")
}

1 个答案:

答案 0 :(得分:3)

您需要一个 lazy 变量,以便能够从闭包内部访问self

lazy var apetureButton: UILabel = { 
   let text = UILabel() 
   let tapLabel = UITapGestureRecognizer(target: self, action: #selector(apetureSelect))
   text.isUserInteractionEnabled = true
   text.addGestureRecognizer(tapLabel)
   text.text = "400" 
   return text
}()