簡體   English   中英

如何使用 StoryBoard 在 UITabBarController 中設置選定的選項卡?

[英]How do I set selected tab in UITabBarController using StoryBoard?

如何使用 StoryBoard 切換到UITabBarController某個選項卡? 我嘗試了下面的代碼但沒有成功(未選擇選項卡):

self.tabBar.selectedIndex = 3;

老實說,我在沒有 StoryBoard 的情況下使用了 nib 文件,上面的代碼在

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
          :(NSDictionary *)launchOptions

但現在我無法以編程方式設置選項卡。 也許還有另一個與選擇選項卡無關的問題。 如何切換標簽頁?

獲取您的UITabBarController實例,然后設置selectedViewController屬性:

yourTabBarController.selectedViewController=[yourTabBarController.viewControllers objectAtIndex:3];//or whichever index you want

亞歷山大,我認為您的問題是獲取標簽欄的正確實例。 如果你的標簽欄是你的根視圖控制器,那么你可以在你的 appdelegate if didFinishLoading 方法中這樣做:

UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
    [tabBar setSelectedIndex:3];

試一試,請告訴我結果。

*Swift Comment - 18 個月后,如果您在 appDelegate 中將 Yanchi 的解決方案轉換為 Swift,您將獲得預期的結果。 Swift 的翻譯是:

let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController

tabBar.selectedIndex = 1

這也適用於故事板......

[self.tabBarController setSelectedIndex:3]; 與此添加UITabBarControllerDelegate.h

然后使用這個delegate方法

- (BOOL)tabBarController:(UITabBarController *)theTabBarController shouldSelectViewController:(UIViewController *)viewController
{
    return (theTabBarController.selectedViewController != viewController);
}

您也可以僅使用情節提要來實現這一點。 按住 Ctrl 從 tabBarController 拖動到您的 ViewController(s),然后選擇“Relationship Segue, View controllers”。 您選擇的第一個 ViewController 將是默認/初始 ViewController。

我在 LSwift 中使用LSwift

extension UITabBarController {
    @IBInspectable var selected_index: Int {
        get {
            return selectedIndex
        }
        set(index) {
            selectedIndex = index
        }
    }
}

斯威夫特 4.1

在您的TabBarViewController類中,您可以添加此關鍵行

self.selectedIndex = 0

這是我所做的(Swift 5.x):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if let tabBarController = self.window?.rootViewController as? UITabBarController {
            if let viewControllers: [UIViewController] = tabBarController.viewControllers {
                tabBarController.selectedIndex = viewControllers.count-1
            }
        }
        return true
    }

斯威夫特 5.3

tabBar成為UITabBarController一個實例,然后:

tabBar.selectedViewController = tabBar.viewControllers![2]

筆記:
而不是 2,把你想要的 viewController 的索引

您還可以使用情節提要在“用戶定義的運行時屬性”中設置默認選項卡。

從情節提要中選擇您的 Tab Bar Controller,在右側窗格中選擇 Identity Inspector 並添加一個屬性:

Key Path : selectedIndex
Type     : Number
Value    : 2 ( whatever number you want )

暫無
暫無

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

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