gpt4 book ai didi

swift - 使用选择器调用带有参数的函数

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

我的 Swift 代码如下所示:

class SystemClass {
public init() {}
func setXYZ(xyz: Float32) {
// do something
}
}

let callME: class = class()
class class {
public init() {}
func functionXYZ() {
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(xyz: 1.0)), userInfo: nil, repeats: true) // error code
}
}

callME.functionXYZ()

我想调用“functionXYZ” ' 这已经工作正常,但调用 setXYZ由于选择器失败,函数会导致错误。

如何编辑选择器:

#selector(SystemClass().setXYZ(xyz: 1.0))

调用setXYZ具有给定参数的函数?

最佳答案

编辑:更新以包含 iOS 10.0 之前的解决方案

在这种情况下,最好使用带有 block 的 scheduledTimer 函数,因为这将允许您将参数传递给函数:

Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in
SystemClass().setXYZ(xyz: 1.0)
}

对于 iOS 10.0 之前的版本:

您还可以传入 userInfo,包括此默认值,然后从选择器内部访问该信息,如下所示:

Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(_:)), userInfo: 1.0, repeats: true)

为此,您还必须修改 setXYZ 函数签名,如下所示:

@objc func setXYZ(_ sender: Timer) {
if let xyz = sender.userInfo as? Float {
print(xyz)
// do something
}
}

关于swift - 使用选择器调用带有参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48102328/

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