从UIAlertController

时间:2018-04-05 16:42:08

标签: ios swift

我的iOS应用中有一个提醒,警报上有两个按钮。我想调用我的函数,当用户选择该选项时调用searchTheWeb():

alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Search The Web!", style: UIAlertActionStyle.default, handler: nil))

func searchTheWeb(){
    let word =  self.userInfo.text! + self.faceResults.text!  + self.labelResults.text!
    if let encoded = word.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: "https://www.google.com/#q=\(encoded)") {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}

所以在addAction中标题为Search The Web!我怎么称呼这个功能?

2 个答案:

答案 0 :(得分:1)

您只需要更改将searchTheWeb操作声明为以下内容的方式:

let search = UIAlertAction(title: "Search The Web!", style: .default) { [weak self] _ in
    self?.searchTheWeb()
}
alert.addAction(search)

答案 1 :(得分:1)

使用警报处理程序

 alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))

let search = UIAlertAction(title: "Search The Web!", style: UIAlertActionStyle.default, handler: { (action) -> Void in
    self.searchTheWeb()
})
alert.addAction(search)

func searchTheWeb(){
    let word =  self.userInfo.text! + self.faceResults.text!  + self.labelResults.text!
    if let encoded = word.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: "https://www.google.com/#q=\(encoded)") {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}