![](/img/trans.png)
[英]Swift - UIButton created programatically doesn't trigger touch event
[英]iOS (Swift): Location of touch event in UIButton programatically
我有一個UIButton
實例,我希望獲得觸摸的確切位置,甚至觸發與其連接的選擇器。
該按鈕的配置如下:
private var button: UIButton!
private func setupButton() {
button = UIButton(frame: frame)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
@objc private func buttonPressed(_ button: BounceButton) {
// I need the location of the touch event that triggered this method.
}
請問用於實現觸發buttonPressed
方法的觸摸事件的位置的方法是什么? 我很猶豫使用UIGestureRecognizer
實例,因為我實際上有多個具有不同tag
值的按鈕,這些按鈕用於在buttonPressed
方法中執行不同的操作。
感謝您的任何建議。
選項1
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: view)
if button.frame.contains(position) {
}
}
}
選項2
添加手勢並訪問按鈕使用
@objc func tapped(_ gesture:UITapGestureRecognizer)
{
print(gesture.view?.tag)
print(gesture.location(in: gesture.view))
}
gesture.view
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.