【问题标题】:Add a call to a function from within a UIAlertController [duplicate]从 UIAlertController 中添加对函数的调用 [重复]
【发布时间】:2018-04-05 16:42:08
【问题描述】:

我的 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!如何调用该函数?

【问题讨论】:

  • 这就是handler 参数的用途????
  • @vadian 我以为我自己调用了句柄中的函数,但这不起作用。在下面查看 AdamPro 的答案,这很有效!
  • 值得一读documentation

标签: ios swift


【解决方案1】:

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

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

【讨论】:

  • 这很有魅力,感谢 Adam!
【解决方案2】:

使用警报处理程序

 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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多