【发布时间】:2017-02-22 10:45:55
【问题描述】:
我正在尝试在网络连接缓慢或断开连接时发出内部应用通知。
如果用户想重新加载,我想调用传入参数的函数(回调),但 Xcode 不允许我这样做:
'#selector' 的参数不能引用参数'callback'
这是我的代码:
func listenForFirebaseConnection(callback: @escaping () -> Void) {
FireDataUtil().getBase().child(".info/connected").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
let isConnected = snapshot.value as! Bool?
if isConnected != nil && isConnected == false {
let view = MessageView.viewFromNib(layout: .MessageView)
view.button?.isHidden = false
// Theme message elements with the warning style.
view.configureTheme(.error)
// Add a drop shadow.
view.configureDropShadow()
// Set message title, body, and icon. Here, we're overriding the default warning
// image with an emoji character.
view.configureContent(title: "Network Issue", body: "It looks like your network connection is either slow or disconnected")
view.button?.setTitle("Reload", for: .normal)
view.button?.addTarget(self, action: #selector(callback), for: .touchUpInside)
var config = SwiftMessages.Config()
config.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
config.presentationStyle = .bottom
config.duration = .seconds(seconds: 5)
// Show the message.
SwiftMessages.show(config: config, view: view)
}
}
})
}
【问题讨论】:
-
你不能像这样调用块方法或闭包。声明块或闭包的属性以按照您尝试的方式调用。
-
我刚刚尝试在这个 anwser 中做类似的事情:stackoverflow.com/a/36983811/6303970 所以我可以这样做:让 myAction = Action { callback() } 和 #selector(myAction.action) 但我得到了“无法识别的选择器发送到实例“
-
您的代码和您关注的帖子有不同的代码,您在函数内部调用操作,这是不可能的。您可以在选择器中调用方法,这些方法要么在类中声明,要么在全局中声明,但不在内部方法中。