gpt4 book ai didi

swift - 选择后 DropDownMenu 中的返回值?

转载 作者:行者123 更新时间:2023-11-30 10:53:06 26 4
gpt4 key购买 nike

我是 Xcode 和 Swift 的新手。我正在使用这个库:https://github.com/PhamBaTho/BTNavigationDropdownMenu在我的应用程序中创建 DropDownMenu 。我按照 Github 上的演示进行操作,一切正常。我试图获取所选值并将其分配给 didSelectItemAtIndexHandler 函数外部的字符串。这是我的代码:

 var menuView: BTNavigationDropdownMenu!

var items = ["San Francisco", "New York", "LA", "Chicago"]


menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: BTTitle.index(0), items: items)

menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> Void in

self. myCity = items[indexPath]
//print(myCity) // prints the correct city every time
}

self.navigationItem.titleView = menuView

我试图在 menuView.didSelectItemAtIndexHandler 之外获取以下内容:

 var test = String()
test = myCity
print(test)

任何帮助将不胜感激。提前致谢!

我正在尝试将数据从这里传递到 TopFiveViewController。

 menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> Void in

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc = storyboard.instantiateViewController(withIdentifier: "TopFiveViewController") as! TopFiveViewController
vc.myCity = self!.items[indexPath]
print(myCity) // prints the correct city every time but it doesn't pass the value to TopFiveViewController!

}

在 TopFiveViewController 中我有:

var myCity = String()

override func viewDidLoad() {
super.viewDidLoad()

if self.myCity == "San Francisco" {

// load SF json file

} else if myCity == "New York" {

// load NY json file

}

最佳答案

正如您提到的,一切都在您的 viewDidLoad() 中发生,我认为了解正在发生的事情很重要。

View 加载和 test 以及 myCity 均设置为 nil

当用户从下拉菜单中选择一个项目时,将调用 menuView.didSelectItemAtIndexHandler 中的代码,并且 myCity 现在将设置为所选值,尽管 test 仍将是 nil,因为设置 myCity 值的完成处理程序对 test 没有影响。

在完成处理程序(其中 self.myCity = items[indexPath] 所在位置)中选择值时,您应该执行您想要执行的任何代码。

关于swift - 选择后 DropDownMenu 中的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245589/

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