gpt4 book ai didi

swift - 如何根据全局变量决定显示哪个 View

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

我正在尝试实现一个 IOS swift 应用程序,该应用程序以选项卡栏 Controller 开始,并且在其中一个选项卡栏 Controller 中有一个名为“帐户”的项目。

当用户按下帐户项时,我希望应用程序根据全局变量“loggedIn”( bool 类型)决定(onclick事件)是显示包含注册/登录的 View 还是显示个人资料 View .

(我尝试过导航 Controller ,但我从中了解到它是一系列 View ,无法在 View 之间做出决定)

我想知道如何实现这一点,也许是某种“路由器”(如果可以的话)可以在 View 之间切换...

如果您不明白,这是我正在尝试实现的内容的图片

Basic Map of what I'm trying to explain

如果您可以建议更专业的方式进行此类设计,请随时表达您的意见。

最佳答案

我相信一个好的方法是在 loggedIn 状态更改时更新 View Controller 。如果您还没有,请创建一个继承自 UITabBarController 的类来管理您的选项卡。代码如下:

class TabController: UITabBarController {}

在 Storyboard中,选择选项卡 Controller ,转到Identity Inspector 并将TabController 设置为自定义类。现在 TabController 将管理标签栏中的所有 View Controller 。

使用全局变量通常不是一个好方法,因此让我们在 TabController 范围中添加 loggedIn 并监听其中的任何更改并更新相应的 View Controller :

class TabController: UITabBarController {
var loggedIn = true {
didSet {
updateProfileTab()
}
}
}

现在,每当您更改 loggedIn 时,该更改都会更新正确的选项卡。现在让我们编写updateProfileTab():

class TabController: UITabBarController {
func updateProfileTab() {
let viewController: UIViewController
if loggedIn {
viewController = makeProfileViewController()
} else {
viewController = makeLoginViewController()
}
setViewController(viewController, at: 2)
}

func makeProfileViewController() -> ProfileViewController {
// create and return the profile view controller
}

func makeLoginViewController() -> LoginViewController {
// create and return the profile view controller
}
}

当然,您可能想要编写 makeProfileViewControllermakeLoginViewController 方法的主体。 TabController 的最后一件事是编写 setViewController(_:at:) 方法:

class TabController: UITabBarController {
...
func setViewController(_ viewController: UIViewController, at index: Int) {
let tabBarItem = viewControllers?[index].tabBarItem
viewController.tabBarItem = tabBarItem
viewControllers?[index] = viewController
}
...
}

现在,由于 TabController 管理您的选项卡栏,因此您可以从其任何 subview Controller 中访问它:

guard let tabController = tabBarController as? TabController else { return }
tabController.loggedIn = ...

此外,选择初始状态也很重要。因此,在选项卡式 View Controller 之一的 viewDidLoad 中,您应该执行上述代码。第一个选项卡(第一个显示的选项卡)可能是执行此操作的最佳位置。希望这有帮助!

编辑

要创建登录和注册 View Controller ,最简单的方法是在 Storyboard中分配 id。为此,请转到 Storyboard,选择 View Controller ,然后在Identity Inspector中设置一个Storyboard ID,您将使用它来实例化 View Controller :

func makeProfileViewController() -> ProfileViewController {
let controller = self.storyboard!.instantiateViewController(withIdentifier: "theStoryboardID")
return controller as! ProfileViewController
}

请注意,我在这里使用强制解包 (!)。这只是为了简洁。在实际情况下,您将需要使用一些 if letguard let 语句来处理 nil 值。

关于swift - 如何根据全局变量决定显示哪个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212720/

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