【问题标题】:Use selector to call function with parameters [duplicate]使用选择器调用带参数的函数[重复]
【发布时间】:2018-01-04 19:35:18
【问题描述】:

我的 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函数?

【问题讨论】:

  • 你不能这样传递参数,选择器等待签名,而不是参数。您可以改用userInfo
  • 请不要回滚有用的编辑。不要使用不相关的标签。不要在标题中添加标签和不必要的评论。我还修复了其他格式。无需撤消所有这些有用且适当的更改。

标签: swift timer


【解决方案1】:

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

在这种情况下,最好使用带有块的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
    }
}

【讨论】:

  • 嗯,看起来不错,但我收到此错误scheduledTimer(withTimeInterval:repeats:block:)' is only available on iOS 10.0 or newer
  • 好的,检查旧 iOS 目标的编辑。
  • 目标不能是self,因为选择器不在同一个类中。
猜你喜欢
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 2014-05-11
相关资源
最近更新 更多