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



我正在尝试在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")
}

你做错了几件事...

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

如果要将标签添加到堆栈视图,则无需设置其框架 - 让堆栈视图处理它。如果您的 stackView 的对齐方式设置为.fill则无论如何它都会将标签拉伸到其宽度。如果未设置为填充,则标签将根据需要根据其文本水平扩展。所以,也没有必要打电话给.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")
}

使用以下代码添加点击手势:

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
}
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或要添加 tap 的任何函数调用addTapGesture()

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

尝试在独立于所有其他控件的控件上添加手势。

最新更新