ios - 从 UITabbarController 中选择选项卡时如何更新 VC 中的值?

标签 ios swift delegates protocols

我有一个标签栏 Controller 。当用户单击选项卡栏按钮之一时,我需要更新目标 View Controller 中的 UIPageViewController 中的值。

我正在尝试使用委托(delegate)来通知 UIPageViewController 单击了哪个选项卡栏按钮:

protocol PlanTypeDelegate {
    func setIntro(thisFlow planType: UITabBarItem)
}

class NewTabBarController: UITabBarController {

var planTypeDelegate : PlanTypeDelegate?

override func viewDidLoad() {
        super.viewDidLoad()

        // create and handle tab bar button actions
}


override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        planTypeDelegate?.setIntro(thisFlow: item)
    }

在我的 UIPageController 我有以下内容:
class IntroPageController: UIPageViewController {

override func viewDidLoad() {
        super.viewDidLoad()

guard let tabbar = self.parent as? NewTabBarController() else { return }
    tabbar.delegate = self

}

}

extension IntroPageController : PlanTypeDelegate {
    func setIntro(thisFlow planType: UITabBarItem) {
        print("this item:\(planType)")
    }
}

相反,我收到此错误消息:
enter image description here

我是在 VC 之间传递数据的新手,所以我不知道如何处理这种情况。

编辑
更新后同样的错误
enter image description here

最佳答案

您可以像这样实现它..无需委托(delegate)...写setIntro IntroPageController 中的方法我希望它能解决你的问题

class NewTabBarController: UITabBarController {
override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self

    }
}
 func tabBarController(_ tabBarController: UITabBarController,
                          shouldSelect viewController: UIViewController) -> Bool{

        if let controller = viewController as? IntroPageController {

            controller.setIntro(thisFlow: tabBarController.tabBarItem)
        }
        return true
    }

你也可以通过Protocol for that write来实现...所有确认PlanTypeDelegate的 Controller 可以针对此方法执行操作
 func tabBarController(_ tabBarController: UITabBarController,
                          shouldSelect viewController: UIViewController) -> Bool{

        if let navController = viewController as? UINavigationController {
            if let myViewController  = navController.topViewController , let homeController = myViewController as? PlanTypeDelegate {
                homeController.setIntro(thisFlow: tabBarController.tabBarItem)
            }
        } else if let controller = viewController as? PlanTypeDelegate {

            controller.setIntro(thisFlow: tabBarController.tabBarItem)
        }
        return true
    }

关于ios - 从 UITabbarController 中选择选项卡时如何更新 VC 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602500/

相关文章:

iOS 7.1 UINavigationBar backgroundImage 行为

ios - 如何在TeamCity中使用iOS Carthage?

swift - View Controller 之间的导航

ios - 选择文本字段时向上滑动的 View 消失,点击键盘时消失

ios - 以半尺寸显示模态视图 Controller

ios - 调用swift后委托(delegate)不执行

wcf - 如何将每个 WCF 调用包装在 try-catch block 中

ios - 在 ViewControllerB 到 ViewControllerA 之间传递数据,委托(delegate)不会被调用

swift - iOS UI 测试 - 选择器轮调整仅滑动一项

macos - NSStatusItem.button (NSStatusBarButton) 的替代方案 OSX 10.9