【问题标题】:how to change background color for selected item in tabBarController如何更改 tabBarController 中所选项目的背景颜色
【发布时间】:2018-01-23 00:54:35
【问题描述】:

我试图改变背景,唯一改变的是图像和标签颜色,我希望背景本身改变成不同的颜色。

例子:

有人知道如何进行此更改吗?

【问题讨论】:

    标签: ios iphone swift tabbarcontroller


    【解决方案1】:

    在您的UITabBarController 中添加以下代码:

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    
        let removeSelectedBackground = {
            tabBar.subviews.filter({ $0.layer.name == "TabBackgroundView" }).first?.removeFromSuperview()
        }
    
        let addSelectedBackground = { (bgColour: UIColor) in
            let tabIndex = CGFloat(tabBar.items!.index(of: item)!)
            let tabWidth = tabBar.bounds.width / CGFloat(tabBar.items!.count)
            let bgView = UIView(frame: CGRect(x: tabWidth * tabIndex, y: 0, width: tabWidth, height: tabBar.bounds.height))
            bgView.backgroundColor = bgColour
            bgView.layer.name = "TabBackgroundView"
            tabBar.insertSubview(bgView, at: 0)
        }
    
        removeSelectedBackground()
        addSelectedBackground(UIColor.green)
    }
    

    它会在所选选项卡所在的任何位置插入green 视图。您也可以使其尊重safeAreaInsets。现在,无论何时选择一个选项卡,它都会从UITabBar 中删除选定的背景视图并添加一个新的在正确的位置。如果您喜欢或从旧位置动画到新位置,您可以每次重复使用相同的视图......无论您喜欢什么。您可以通过标签而不是图层名称来识别视图,但这只是个人喜好。

    【讨论】:

    • 如何将第一个选项卡设置为在初始加载时选择的?
    【解决方案2】:

    你可以试试这样的:

    UITabBar.appearance().backgroundColor = .white
    UITabBar.appearance().tintColor = .green // or whatever your green is
    

    这将使应用程序中的所有标签栏在实例化时默认为这些颜色。

    注意:我还没有测试过。

    【讨论】:

      【解决方案3】:

      为什么不为每个 tabBarItem 设置两张图片,其中一张图片用于 默认 状态,另一张用于 selected 状态。在您的情况下,选定状态为白色,默认为绿色。

      您可以通过 UIBarItem 的 store 属性 var selectedImage: UIImage? { get set } 或构造函数/初始化器 init(title: String?, image: UIImage?, selectedImage: UIImage?) 为您的 UIBarItem 设置这些图像。

      【讨论】:

      • 谢谢,我会做一个白色背景和中间图标的图像
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      相关资源
      最近更新 更多