【发布时间】:2019-02-14 14:47:26
【问题描述】:
我正在尝试重构我的UIAlertViewController,并在用户选择点击触发操作的两个选项之一时传递一个要执行的函数。
我的问题是如何将函数作为参数添加到自定义函数?我的努力在下面。它不完整,但任何指导将不胜感激。我想将函数 'performNetworkTasl' 作为 'showBasicAlert' 的参数。
import Foundation
import UIKit
struct Alerts {
static func showBasicAlert(on vc: UIViewController, with title: String, message: String, function: ?????){
let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction.init(title: "OK", style: .default) { (UIActionAlert) in
performNetworkTasl()
vc.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
}
}
func performNetworkTasl(){
// DO SOME NETWORK TASK
}
【问题讨论】:
-
okAction下面已经调用了,为什么还要把函数作为参数传递?
-
应该是参数
function: @escaping () -> Void。它将接受具有相同签名() -> Void的闭包/函数要调用它:showAlert(on: vc, with: "", message: "", function: performNetworkTasl)
标签: ios swift function uialertviewcontroller