【发布时间】:2021-12-30 19:46:32
【问题描述】:
我正在处理使用 UITabBarController 的问题。我有一个使用故事板的小项目(XCode 13,IOS 15 作为基本系统)。我创建了一个 TabBarController,但后来我发现我无法以编程方式有效地管理它。阅读各种文档后,我发现我可以使用故事板中的两个场景并以编程方式创建标签栏。
所以我在SceneDelegate.swift:
let queryViewControllerTab = storyBoard.instantiateViewController(withIdentifier: "QueryViewController")
let settingsViewControllerTab = storyBoard.instantiateViewController(withIdentifier: "SettingsViewController")
let starredViewControllerTab = storyBoard.instantiateViewController(withIdentifier: "StarredViewController")
starredViewControllerTab.tabBarItem.title = "Starred"
starredViewControllerTab.tabBarItem.image = UIImage(systemName: "star")
// TODO: Discover why first two views keep reading image I setup previously in storyboard
let tabBarController = UITabBarController()
tabBarController.viewControllers = [queryViewControllerTab, settingsViewControllerTab, starredViewControllerTab]
tabBarController.selectedViewController = settingsViewControllerTab
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
这很好用,我可以很容易地设置一个条件是否userDefaults 没有设置,直接加载设置。
在我的班级SettingsViewController 我想添加一个动作,在按下按钮时,您会收到警报:
@IBAction func saveButtonPressed(_ sender: UIButton) {
// keychain.set(tokenInput.text ?? "", forKey: keychainKey)
let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"),
style: .default, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
tabBarController.present(alert, animated: true, completion: nil)
}
但这会使应用程序因unrecognized selector sent to instance 0x7f82f9705c30'而崩溃
我已尝试调试问题,但我明白我无法以这种方式发出警报,因为视图实际上是 tabBar 而不是我的场景。但在这里我卡住了。
我尝试在StarredViewController 中实现UITabBarControllerDelegate,但无法正常工作。
extension StarredViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
print("did select tab bar item!")
}
}
我开始认为我使用SceneDelegate 和AppDelegate 的主要设置是错误的。
我发现的大多数以前的教程或线程似乎都无法编译,因为使用了已弃用的版本。
【问题讨论】:
标签: ios swift storyboard uitabbarcontroller