gpt4 book ai didi

swift - 从闭包中呈现 View Controller

转载 作者:行者123 更新时间:2023-11-28 12:14:02 26 4
gpt4 key购买 nike

我有一个闭包作为添加到 UIAlertController 的项目的处理程序。我按预期收到闭包内的 id 值。 (我没有在代码片段中使用它)。

但我遇到的问题是我想切换到另一个 View Controller 。但是我在闭包内进行了这个调用。

我收到以下错误: 类型“(ChooseProfile) -> () -> (ChooseProfile)”的值没有成员“present

如何从我的闭包中切换到另一个 View Controller ?

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。

最佳答案

问题是您在闭包中使用了 self,但 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)
}

关于swift - 从闭包中呈现 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com