Swift WatchOS 等待用户输入
Swift WatchOS Wait for user input
@IBAction func switchedButton(value: Bool) {
dump(self.showPopup("Test"))
}
func showPopup(textMessage: String) -> Bool {
let action1 = WKAlertAction(title: "Approve", style: .Default) { () -> Void in
return true
}
let action2 = WKAlertAction(title: "Cancel", style: .Cancel) { () -> Void in
return false
}
presentAlertControllerWithTitle("Confirm", message: textMessage, preferredStyle: .ActionSheet, actions: [action1, action2])
return false
}
这将始终 return 错误。我如何才能等待用户 select 批准或取消?
它总是 return 是错误的,因为当用户点击某个操作时,showPopup
方法已经 returned。它实质上使该方法异步。
请注意,WKAlertAction
上的回调未指定 return 值,因此您不能 return
从中获取任何内容。
您要做的是将回调块传递给 showPopup
,您可以在用户交互时调用它:
@IBAction func switchedButton(value: Bool) {
self.showPopup("Test") { result in
// result is a bool
}
}
// callback expects a single Bool parameter
func showPopup(textMessage: String, callback: (Bool) -> ()) {
let action1 = WKAlertAction(title: "Approve", style: .Default) { () -> Void in
callback(true)
}
let action2 = WKAlertAction(title: "Cancel", style: .Cancel) { () -> Void in
callback(false)
}
presentAlertControllerWithTitle("Confirm", message: textMessage, preferredStyle: .ActionSheet, actions: [action1, action2])
}
@IBAction func switchedButton(value: Bool) {
dump(self.showPopup("Test"))
}
func showPopup(textMessage: String) -> Bool {
let action1 = WKAlertAction(title: "Approve", style: .Default) { () -> Void in
return true
}
let action2 = WKAlertAction(title: "Cancel", style: .Cancel) { () -> Void in
return false
}
presentAlertControllerWithTitle("Confirm", message: textMessage, preferredStyle: .ActionSheet, actions: [action1, action2])
return false
}
这将始终 return 错误。我如何才能等待用户 select 批准或取消?
它总是 return 是错误的,因为当用户点击某个操作时,showPopup
方法已经 returned。它实质上使该方法异步。
请注意,WKAlertAction
上的回调未指定 return 值,因此您不能 return
从中获取任何内容。
您要做的是将回调块传递给 showPopup
,您可以在用户交互时调用它:
@IBAction func switchedButton(value: Bool) {
self.showPopup("Test") { result in
// result is a bool
}
}
// callback expects a single Bool parameter
func showPopup(textMessage: String, callback: (Bool) -> ()) {
let action1 = WKAlertAction(title: "Approve", style: .Default) { () -> Void in
callback(true)
}
let action2 = WKAlertAction(title: "Cancel", style: .Cancel) { () -> Void in
callback(false)
}
presentAlertControllerWithTitle("Confirm", message: textMessage, preferredStyle: .ActionSheet, actions: [action1, action2])
}