UITabBarController仅显示第一个选项卡

时间:2016-12-09 21:26:10

标签: swift tvos

我正在重新考虑,因为UITabbarController showing only first tab中的问题没有得到解答......我不明白为什么我的UITabBarController只显示第一个标签。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.darkGray
        self.window?.makeKeyAndVisible()
        let tab = UITabBarController()
        let v1 = VC1(nibName: "View1", bundle: nil)
        let v2 = VC2(nibName: "View2", bundle: nil)
        let v3 = VC3(nibName: "View3", bundle: nil)
        let myViews = [v1,v2,v3]
        tab.viewControllers = myViews
        self.window?.rootViewController = tab 
        return true
    }

}

VC1代码:

class VC1: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("view 1 will load")
        self.title = "View 1"
        // Do any additional setup after loading the view.
    }

}

类VC2:

class VC1: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("view 2 will load")
        self.title = "View 2"
        // Do any additional setup after loading the view.
    }

}

VC3:

class VC1: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("view 3 will load")
        self.title = "View 3"
        // Do any additional setup after loading the view.
    }

}

我认为这是一种经过测试和验证的方法来创建标签但它似乎不起作用,这是结果屏幕截图

Result Screenshot

2 个答案:

答案 0 :(得分:2)

UITabBarController使用每个视图控制器中的title来创建屏幕上显示的标签。这里的问题是,在调用title之前,您的视图控制器没有viewDidLoad属性的任何值,这太晚了。

您应该在初始化期间设置title属性; initWithNibName:bundle:将是一个很好的地方。

答案 1 :(得分:0)

我找到了一种更清晰的方法来实现这一点,View Controller的标题是一个属性,可以在它实例化之后立即设置

所以更新后的代码如下:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.darkGray
        self.window?.makeKeyAndVisible()
        let tab = UITabBarController()
        let v1 = VC1(nibName: "View1", bundle: nil)
        let v2 = VC2(nibName: "View2", bundle: nil)
        let v3 = VC3(nibName: "View3", bundle: nil)
        v1.title = "View 1"
        v2.title = "View 2"
        v3.title = "View 3"
        let myViews = [v1,v2,v3]
        tab.setViewControllers(myViews, animated: false)
        self.window?.rootViewController = tab 
        return true
    }

}

屏幕截图是:

3 Views TabBarController

相关问题