我有一个函数,它创建一个以选择器函数为目标的按钮。按钮的地址被传递到handleSelectPhoto

lazy var image1Button = createButton(selector: #selector(handleSelectPhoto))
func createButton(selector: Selector) -> UIButton {
    let button = UIButton(type: .system)
    button.addTarget(self, action: selector, for: .touchUpInside)
    return button
}
@objc func handleSelectPhoto(button: UIButton) {
    // Do something with button, this works
}

现在,我试图将上面的类从UIButton更改为UIImageView,如下所示,
lazy var image1Button = createButton(selector: #selector(handleSelectPhoto))
func createButton(selector: Selector) -> UIImageView {
    let view = UIImageView()
    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: selector))
    view.isUserInteractionEnabled = true
    return view
}
@objc func handleSelectPhoto(button: UIImageView) {
    // HERE, button does not get passed
}

有了上述更改,在handleSelectPhoto中,按钮实例不正确。我无法将其读取为UIImageView类型。
如果我使用addGestureRecognizer添加选择器函数,就如何使用参数执行选择器函数而言,它的行为是否与使用addTarget添加选择器函数不同?也许我不明白这个选择器函数是如何工作的。。。

最佳答案

在设置选择时,应该通过在方法名末尾添加:来告知函数将接受参数。

lazy var image1Button = createButton(selector: #selector(handleSelectPhoto:))

UIKit将自动理解选择器方法参数的类型为UITapGestureRecognizer。现在像这样重写下面的方法,你就可以开始了。
@objc func handleSelectPhoto(gesture: UITapGestureRecognizer) {
        if let buttonImageView = gesture.view as? UIImageView {
            //Here you can make changes in imageview what ever you want.
        }
}

关于swift - addTarget和addGestureRecognizer之间的行为不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54882088/

10-15 14:09