以编程方式将点击手势添加到 UILabel

add tap gesture to a UILabel Programmatically

我正在尝试在 swift 4 中的函数中为动态创建的 UILabel 添加点击手势,但它没有触发 UITapGestureRecognizer 函数。当我从 viewDidLoad 函数添加点击手势时它可以工作,但我必须从其他函数添加点击手势。

这是代码

    override func viewDidLoad() {

    super.viewDidLoad()

    createLabel()
    }

   func createLabel() {

   let label = UILabel()
   label.text = "abc"
   label.numberOfLines = 0 
   label.frame.size.width = self.otherlinksStack.bounds.width
   label.font = label.font.withSize(17) // my UIFont extension

   label.sizeToFit()
   label.tag = 1
   self.otherlinksStack.addSubview(label)
   let labelTapGesture = UITapGestureRecognizer(target:self,action:#selector(self.doSomethingOnTap))

 label.isUserInteractionEnabled = true

 label.addGestureRecognizer(labelTapGesture)

 }

 @objc func doSomethingOnTap() {

    print("tapped")
}

如果您的手势在 viewDidLoad 中有效,那么在从其他函数添加后,该手势可能会被其他控件的手势覆盖。

尝试在与所有其他控件分开的控件上添加手势。

func addTapGesture() {
  let labelTapGesture = UITapGestureRecognizer(target: self, action: #selector(doSomethingOnTap))
  //Add this line to enable user interaction on your label 
  myLabel.isUserInteractionEnabled = true
  myLabel.addGestureRecognizer(labelTapGesture)
}
    
@objc func doSomethingOnTap() {
  print("tapped")
}

然后从 viewDidLoad 或任何您想从中添加点击的函数调用 addTapGesture()

使用此代码添加点击手势:

let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureMethod(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
yourLabel.isUserInteractionEnabled = true
yourLabel.addGestureRecognizer(tapGesture)

这是点击手势方法:

@objc func tapGestureMethod(_ gesture: UITapGestureRecognizer) {
    Do your code here
}

你做错了几件事...

// your code
label.frame.size.width = self.otherlinksStack.bounds.width
label.sizeToFit()

如果您要将标签添加到 stackView,则无需设置其框架——让堆栈视图处理。如果您的 stackView 的对齐方式设置为 .fill,它无论如何都会将标签拉伸到其宽度。如果 not 设置为填充,标签将根据其文本按需要水平扩展。因此,也无需调用 .sizeToFit().

// your code
self.otherlinksStack.addSubview(label)

将视图添加到堆栈视图时,请使用.addArrangedSubview,否则它将被添加到堆栈视图中另一个视图的顶部。

这应该可以正常工作(在我的快速测试中确实如此):

func createLabel() {

    let label = UILabel()

    label.text = "abc"
    label.numberOfLines = 0
    label.font = label.font.withSize(17) // my UIFont extension
    label.tag = 1

    // give the label a background color so we can see it
    label.backgroundColor = .cyan

    // enable user interaction on the label
    label.isUserInteractionEnabled = true

    // add the label as an Arranged Subview to the stack view
    self.otherlinksStack.addArrangedSubview(label)

    // create the gesture recognizer
    let labelTapGesture = UITapGestureRecognizer(target:self,action:#selector(self.doSomethingOnTap))

    // add it to the label
    label.addGestureRecognizer(labelTapGesture)

}

@objc func doSomethingOnTap() {
    print("tapped")
}