如何在自定义视图中添加MDCTabBar?

How to add MDCTabBar in the custom view?

我在 iOS 中使用 Material Design 库,我试图在导航栏下方的自定义视图中添加 MDCTabBar 但它不起作用.代码就像

let tabBar = MDCTabBar(frame: self.mainTabBar.bounds)
    tabBar.items = [
        UITabBarItem(title: "TAB 1", image: nil, tag: 0),
        UITabBarItem(title: "TAB 2", image: nil, tag: 1),
    ]
    tabBar.tintColor = UIColor.white
    tabBar.barTintColor = UIColor.theme
    tabBar.alignment = .justified
    tabBar.itemAppearance = .titles
    tabBar.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    tabBar.displaysUppercaseTitles = true
    tabBar.sizeToFit()
    self.mainTabBar.addSubview(tabBar)

这里mainTabBar是我的自定义视图,它就在导航栏的正下方。请帮助解决这个问题。

提前致谢!

您的 ViewController class 必须从 MDCTabBarViewController class 继承,例如:

    class SelectTeamViewController: MDCTabBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
}

那么它应该是可见的。 您甚至可以将故事板中的 UIView 和身份检查器中的 select MDCTabBar class 拖动

let tabBar = MDCTabBar(frame: self.mainTabBar.bounds)
tabBar.delegate = self
tabBar.items = [
        UITabBarItem(title: "Tab 1", image: nil, tag: 0),
        UITabBarItem(title: "Tab 2", image: nil, tag: 1),
    ]
tabBar.tintColor = UIColor.white
tabBar.barTintColor = UIColor.theme
tabBar.alignment = .justified
tabBar.itemAppearance = .titles
tabBar.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
tabBar.displaysUppercaseTitles = true
tabBar.sizeToFit()
self.mainTabBar.addSubview(tabBar)

这里 mainTabBar 是我的自定义视图,它就在导航栏的正下方。

Swift 4:

为什么我没有看到我的 tabBar 有两个原因!

  • 第一个是我没有选择与我的容器(tabBarView)颜色不同的颜色,所以它是白色 tabBar,白色 tabBarView 上有白色文本。
  • 其次是一件棘手的事情,它与之前的其他答案不同。我将 MDCTabBar 框架设置为 view.bounds,然后使用 sizeToFit 方法将其压缩到容器 tabBarView 大小。这是唯一让我在屏幕上处于正确位置的东西!欢迎您调整一些属性并在您的代码中使用它!阅读您的评论会很有趣!

    func setTabBar() {
    
    // Set our MDCTabBar frame equal to view.bounds
    let tabBar = MDCTabBar(frame: view.bounds)
    tabBar.delegate = self
    tabBar.items = [
        UITabBarItem(title: NSLocalizedString("FirstTab", comment: ""), image: nil, tag: 0),
        UITabBarItem(title: NSLocalizedString("SecondTab", comment: ""), image: nil, tag: 1)
    ]
    tabBar.itemAppearance = .titles
    tabBar.barTintColor = .yellow
    tabBar.tintColor = .green
    tabBar.setTitleColor(.black, for: .normal)
    tabBar.setTitleColor(.blue, for: .selected)
    tabBar.displaysUppercaseTitles = false
    tabBar.alignment = .justified
    
    // This sizeToFit will squash our MDCTabBar to tabBarView size
    tabBar.sizeToFit()
    // Add MDCTabBar to our tabBarView as a subview
    tabBarView.addSubview(tabBar)
    

    }