很确定这是一个简单的,在互联网上仍然找不到类似的东西 - 更有理由相信这是一个非问题。无论如何!
我怎么能在视图中调用函数的同时put a UIButton
inside a UIView
并添加一个UITapGestureRecognizer
,同时仍然执行按钮操作?
是)我有的:
我想要的是:
更新(我使用的代码):
import UIKit
import AwesomeFramework
class View: UIView {
let button = UIButton()
let awesomeObject = AwesomeFramework.AwesomeObject()
@objc func a(_ sender: Any) {
// never gets called
print("a")
}
init() {
super.init(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
addSubview(button)
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: centerXAnchor),
button.centerYAnchor.constraint(equalTo: centerYAnchor),
button.widthAnchor.constraint(equalTo: widthAnchor),
button.heightAnchor.constraint(equalTo: heightAnchor),
])
button.addTarget(awesomeObject, action: #selector(awesomeAction), for: .touchUpInside) // awesomeAction prints "b"
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(a(_:)))
addGestureRecognizer(gestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
点击我想要的按钮:
b
a
要么
a
b
我明白了:
b
更新:调整示例有一些限制,例如:
一个按钮可以有多个目标。告诉按钮触发a
和b
:
button.addTarget(self, action: #selector(a), for: .touchUpInside)
button.addTarget(self, action: #selector(b), for: .touchUpInside)
如果用户将手指放在按钮中,然后在释放之前拖出按钮怎么办?如果你想要同时触发a
动作,也可以这样做:
button.addTarget(self, action: #selector(a), for: .touchUpOutside)
在UITapGestureRecognizer的你选择器中,你可以检查哪个视图是从中触发的手势。由于您可以访问该视图,因此您可以检查发送视图的标记,并确定它是否是由您的按钮触发的。
这是你如何做到的:
@objc func a(_ sender: Any) {
if let gesture = sender as? UITapGestureRecognizer, let v = gesture.view, v.tag == self.button.tag {
return //since it has the tag same as that you had set for button, return
}
// else do what you wanted to.
}
您可以将选择器链接为:
#selector(a(_:))
并定义为:
func a(_ sender: Any) { .....}
务必通过以下方式标记您的按钮:
self.button.tag = 9 //(or any number you prefer)