Swift - 如果条件满足,转到特定视图

Swift - Segue to a specific view if conditions met

我有一个选项卡栏,其中包含一个指向导航控制器的项目,其中包含用户朋友的列表。然而,虽然匿名用户应该能够浏览该应用程序,但我只希望登录用户能够查看好友列表,因为只有这样他们才会有朋友。我使用 Parse 作为后端,所以我可以测试 PFUser.currentUser(),但我不知道如何告诉导航控制器转至提示用户登录 in/sign 的 VC如果他们还没有的话。提前致谢。

编辑:我已经在选项卡栏控制器 class 中实施了建议的解决方案,看起来像这样:

override func viewDidLoad() {
    super.viewDidLoad()
    tabBarController?.delegate = self
}

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
    if viewController == FriendsTableViewController() {
        if PFUser.currentUser() != nil {
            println("there is a logged in user")
            return true
        } else {
            let authVC:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("auth") as UIViewController
            presentViewController(authVC, animated: true, completion: nil)
            println("attempted to present auth vc")
            return false
        }
    } else {
        println("not friends table vc")
        return true
    }
}

但是,当我select朋友栏项目时没有任何输出。我错过了什么?

编辑:已解决。这是朋友的视图控制器中viewWillAppear的代码vc:

override func viewWillAppear(animated: Bool) {
    if PFUser.currentUser() == nil {
        var login = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("auth") as AuthenticationVC
        self.presentViewController(login, animated: animated, completion: nil)
    }
}

UITabBarControllerDelegate 有一个可行的委托方法。您可以使用委托提供的 viewController 变量进行检查。

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
    if viewController == FriendListViewController() {
        if PFUser.currentUser() != nil {
            return true
        }
        else {
            // Prompt login/signup
            return false
        }
    }
}

我通常完成此操作的方法,这适用于有和没有标签栏的应用程序,是在目标视图控制器中有某种​​需要身份验证标志,如果用户未登录,则存在模态登录屏幕。

例如在朋友列表视图控制器中(假设使用情节提要但没有太大区别):

override func viewWillAppear(animated: Bool) {
    if PFUser.currentUser() == nil {
        var login = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController
        //set properties of login 
        self.presentViewController(login, animated: YES)
    }
}

(或使用 performSegue)

恕我直言,模式呈现样式在这里更合适,因为它就像是用户体验的切线。