簡體   English   中英

從 UITabbarController 選擇選項卡時如何更新 VC 中的值?

[英]How to update the value in a VC when a tab is selected from a UITabbarController?

我有一個標簽欄 controller。當用戶單擊其中一個標簽欄按鈕時,我需要更新目標視圖 controller 中的 UIPageViewController 中的值。

我正在嘗試使用委托來通知 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)")
    }
}

相反,我收到此錯誤消息: 在此處輸入圖像描述

我不熟悉在 VC 之間傳遞數據,所以我不知道如何 go 處理這種情況。

更新后編輯同樣的錯誤在此處輸入圖像描述

你可以像這樣實現它......沒有委托......在IntroPageController中編寫setIntro方法我希望它能解決你的問題

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
    }

您也可以通過該寫入的協議來實現它...所有確認PlanTypeDelegate的控制器都可以針對此方法執行操作

 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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM