从UITabBarController呈现ViewController标签

时间:2015-11-29 15:33:06

标签: ios swift uitabbarcontroller viewcontroller

我是使用swift编程IOS应用程序的新手。 我已经使用代码在AppDelegate.swift中编写了TabBar,并在MainPageViewController.swift和DetailViewController.swift中使用了2个ViewControllers程序。

    let tabBarController = UITabBarController()
    let mainPageVC = MainPageViewController()
    let detailVC = DetailViewController()
    tabBarController.viewControllers = [mainPageVC,detailVC]
    let mainTabBar = UITabBarItem(title: nil, image: UIImage(named: "03")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "06")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))
    let detailTabBar = UITabBarItem(title: nil, image: UIImage(named: "02")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "05")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))
    mainPageVC.tabBarItem = mainTabBar
    deviceVC.tabBarItem = deviceTabBar
    mainPageVC.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
    deviceVC.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
    UITabBar.appearance().barTintColor = UIColor(red: 211/255, green: 1, blue: 246/255, alpha: 1)
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window?.rootViewController = tabBarController
    self.window?.makeKeyAndVisible()

然后我在MainPageViewController.swift中添加了一个Label

class MainPageViewController: UIViewController {
@IBOutlet weak var testLabel: UILabel!
@IBOutlet weak var mainTabBarItem: UITabBarItem!
override func viewDidLoad() {
    super.viewDidLoad()
    let backgraondLayer = color.gl
    backgraondLayer.frame = view.frame
    self.view.layer.insertSublayer(backgraondLayer, atIndex: 0)
    testLabel.backgroundColor = UIColor.blackColor()
}

我不断收到“致命错误:在展开Optional值时意外发现nil”错误。 如果我删除“Label.backgroundColor”代码并在Attribute Inspector中设置背景颜色,Build App将不会显示Label。

我错过了什么代码? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果testLabel.backgroundColor = UIColor.blackColor()中的“在解包可选值时”为您提供“nil”,则可能是您的标签未连接到Interface Builder中的控件。在编辑器中,IBOutlets在声明旁边有一个小圆圈。清空一个未连接,圆圈内点连接。

如果您仍处于app dev的开头,请考虑在Interface Builder / Storyboard中执行UITabBarController管道。每次添加新选项卡时,它都可以帮助您避免一些无聊的工作。