Swift WatchOS等待用户输入

时间:2015-08-19 11:28:57

标签: xcode swift watchkit watch-os-2

@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

}

这将始终返回false。我如何等待用户选择批准或取消?

1 个答案:

答案 0 :(得分:1)

它总是返回false,因为当用户点击某个操作时,showPopup方法已经返回。它本质上使这个方法异步。

请注意WKAlertAction上的回调未指定返回值,因此您无法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])
}