gpt4 book ai didi

swift - Swift 中的手动 GestureRecognizer 处理程序不能有参数吗?

转载 作者:行者123 更新时间:2023-11-30 10:17:53 25 4
gpt4 key购买 nike

如果我通过 InterfaceBuilder 创建 GestureRecognizer 处理程序,我会得到一个如下所示的方法:

    @IBAction func Tap(tap: UITapGestureRecognizer) {
var touchLocation = tap.locationInView(self.view)
imageView.transform.tx = touchLocation.x
imageView.transform.ty = touchLocation.y
}
//works great

如果我手动创建 GestureRecognizer,我必须创建一个不带参数的函数,如下所示:

    let tap = UITapGestureRecognizer()

override func viewDidLoad() {
super.viewDidLoad()

let imageSize = CGSize(width: 100, height: 100)
var iView = UIImageView(frame: CGRect(origin: CGPoint(x: 100, y: 100), size: imageSize))
self.view.addSubview(iView)
let image2 = UIImage(named: "square.png");
iView.image = image2

iView.userInteractionEnabled = true
iView.addGestureRecognizer(tap)
tap.addTarget(self, action: "Tap")
}

func Tap( //why can't I put an argument in here?// ){
let tapAlert = UIAlertController(title: "Tap Pressed", message: "You just tapped", preferredStyle: .Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
//works but I've lost access to the sending object

如果我向 Tap 处理程序添加参数

func Tap(sender: UITapGestureRecognizer){

}
//crashes: [tapHandler]: unrecognized selector sent to instance

,它在点击时崩溃。我更喜欢有一个可以访问发送者对象的方法。有没有办法手动创建 GestureRecognizer 处理程序并访问发送者对象,就像通过 Interface Builder 执行此操作时一样?

最佳答案

选择器名称是 Swift 从 Objective C 继承的。在 Objective C 中,具有单个参数的选择器的名称为 selector: ,与 selector 相反,这意味着 - 不论据。将 addTarget 中的操作名称从 Tap 更改为 Tap:,然后它就应该可以工作了。

关于swift - Swift 中的手动 GestureRecognizer 处理程序不能有参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com