我有一个闭包作为添加到UIAlertController的项的处理程序。我按预期收到了闭包内的id值。 (我不会在代码段中使用它。)
但我遇到的问题是我想切换到另一个视图控制器。但我在封闭内部做了这个调用。
我收到以下错误:
Value of type '(ChooseProfile) -> () -> (ChooseProfile)' has no member 'present
'
如何从闭包中切换到另一个视图控制器?
class ChooseProfile: UIViewController {
let closure = { (id: String) in { (action: UIAlertAction!) -> Void in
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "test") as! UIViewController
self.present(nextViewController, animated:true, completion:nil)
}}
}
我使用这个闭包是因为:
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: "Choose a Device", message: "Which device would you like to use in this app?", preferredStyle: UIAlertControllerStyle.alert)
for dev in (DataSingleton.instance.getDevices())! {
alert.addAction(UIAlertAction(title: dev.getName(), style: UIAlertActionStyle.default, handler: closure(dev.getId())))
}
alert.addAction(UIAlertAction(title: "Add a new Profile", style: UIAlertActionStyle.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
我根据设备列表添加警报操作。我想在点击设备时检索id。
答案 0 :(得分:2)
问题是你在关闭时使用self,但是自己并没有引用VC的实例,因为它还没有完全创建。相反,为什么不在调用它时将viewController传递给闭包呢?
class ChooseProfile: UIViewController {
let closure = { (id: String, vc: UIViewController) in { [weak vc] (action: UIAlertAction!) -> Void in
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "test")
vc?.present(nextViewController, animated:true, completion:nil)
}}
}
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: "Choose a Device", message: "Which device would you like to use in this app?", preferredStyle: UIAlertControllerStyle.alert)
for dev in (DataSingleton.instance.getDevices())! {
alert.addAction(UIAlertAction(title: dev.getName(), style: UIAlertActionStyle.default, handler: closure(dev.getId(), self)))
}
alert.addAction(UIAlertAction(title: "Add a new Profile", style: UIAlertActionStyle.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}