Swift - 如何使用 UILongPressGestureRecognizer 获取一组按钮的发送者标签?

Swift - How to get the sender tag for an array of buttons using UILongPressGestureRecognizer?

我在情节提要中有一些按钮,我将它们放入了引用插座集合中。我对所有这些按钮都使用了 UITapGestureRecognizer 和 UILongPressGestureRecognizer,但是我怎样才能准确地打印出哪个按钮被点击了呢?贝娄是我试过但没有用的。我收到一条错误消息,显示 "Value of type 'UILongPressGestureRecognizer' has no member 'tag'." 我正在尝试为扫雷游戏构建按钮网格。感谢您的帮助。

class ViewController: UIViewController { @IBOutlet var testButtons:[UIButton]! // 这个数组中有 100 个按钮

override func viewDidLoad() {
    super.viewDidLoad()

    let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
    testButtonPressed.minimumPressDuration = 0.5
    // These indexes are just to test how to recognize which button gets pressed
    testButtons[0].addGestureRecognizer(testButtonPressed)
    testButtons[1].addGestureRecognizer(testButtonPressed)

}

@objc func testPressed(_ sender: UILongPressGestureRecognizer) {
    print("Test button was pressed")

    print(sender.tag) // THIS DOESN'T WORK, BUT CONCEPTUALLY THIS IS WHAT I WANT TO DO
}

而不是使用手势我认为使用@IBAction 并将按钮与其连接会更好here is a small example

出现此错误是因为 UILongPressGestureRecognizer 对象没有 tag 属性

您可以通过以下方式访问发件人按钮:

@objc func testPressed(_ sender: UILongPressGestureRecognizer) {
    guard let button = sender.view as? UIButton else { return }
    print(button.tag)
}

我认为处理按钮操作的最佳解决方案是添加 @IBAction (您可以像 @IBOutlet 一样添加它,稍作更改 - 设置 Action 连接类型)

然后在 @IBAction 块中,您可以访问所有按钮属性(如 tag 和其他)

UILongPressGestureRecognizer 是 UIGestureRecognizer 的子类,每个按钮或视图只能使用一次。因为 UILongPressGestureRecognizer 只有一个视图 属性。在您的代码中,它始终是 testButtons[1] 调用 testPressed 操作。所以你必须首先像这样修改 viewDidLoad 代码:-

for button in testButtons {
        let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
        testButtonPressed.minimumPressDuration = 0.5
        button.addGestureRecognizer(testButtonPressed)
        button.addGestureRecognizer(testButtonPressed)
    }

然后你可以像这样从 testPressed 访问按钮(我希望你已经在故事板中设置了标签):-

@objc func testPressed(_ sender: UILongPressGestureRecognizer) {

    if sender.state == .began {
        if let button = sender.view as? UIButton {
            print(button.tag)
        }
    }
}

点击前需要设置标签! 在 viewDidLoad() 方法中,您必须添加如下内容:

testButtons.enumerated().forEach {
     let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
     testButtonPressed.minimumPressDuration = 0.5
     [=10=].element.addGestureRecognizer(testButtonPressed)
     [=10=].element.tag = [=10=].offset
}

当长按接收时,您需要从视图而不是发送者那里获取标签!

print(sender.view?.tag)