【问题标题】:Change background color of UITabBarItem in Swift [duplicate]在Swift中更改UITabBarItem的背景颜色[重复]
【发布时间】:2018-01-01 19:22:10
【问题描述】:

我只想更改其中一个选项卡蝙蝠项目的背景颜色。我找到了很多链接,但没有得到任何帮助。

要求:

而且,这就是我设置标签栏项目的方式

 let myTabBarItem3 = (self.tabBar.items?[2])! as UITabBarItem
 myTabBarItem3.image = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
 myTabBarItem3.selectedImage = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)

我想要的是中心标签栏项目的黑色背景。

有什么想法吗?

是的,它不是重复的,因为之前的回答不准确,添加额外的子视图从来都不是一个好的选择,所以期待朋友们提供一些好的解决方案

【问题讨论】:

    标签: ios swift background-color uitabbar uitabbaritem


    【解决方案1】:

    你可以使用imageView来实现这个效果,试试这个方法

    let myImageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    // Now add this imageView as subview and apply constraints
    tabbar.addSubview(myImageView)
    myImageView.translatesAutoresizingMaskIntoConstraints = false        
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0(28)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": myImageView]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v0(28)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": myImageView]))
    
    tabbar.myImageView.image = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
    tabbar.myImageView.tintColor = UIColor.black
    

    【讨论】:

    • 这里的addconstraints是什么??
    • 这个方法会在视图上添加约束,
    • 我知道但这里有什么用
    • 这个方法会在 imageView 的父视图上调用,我假设它是tabbar
    • 这些约束只会设置框架,然后我们才能在屏幕上看到 imageView
    【解决方案2】:

    如果您只想更改中心tabBarItem 的背景颜色,您可以按照以下代码进行操作。

    注意:以下所有代码都在自定义类中使用,该类将 UITabBarController 扩展为:

    class tabbarVCViewController: UITabBarController, UITabBarControllerDelegate {
    
        // MARK: - ViewController Override Methods.
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
    
            setupInitilView()
        }
    
        // MARK: - setup Initial View Methode.
        private func setupInitilView() {
    
            delegate = self
    
            // Sets the default color of the icon of the selected UITabBarItem and Title
            UITabBar.appearance().tintColor = UIColor.white
    
            // Sets the default color of the background of the UITabBar
            UITabBar.appearance().barTintColor = UIColor.white
    
            // Sets the background color of the selected UITabBarItem (using and plain colored UIImage with the width = 1/5 of the tabBar (if you have 5 items) and the height of the tabBar)
            //UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(color: UIColor.black, size: CGSize.init(width: tabBar.frame.width/4, height:  tabBar.frame.height))
    
    
            // Uses the original colors for your images, so they aren't not rendered as grey automatically.
            for item in self.tabBar.items! {
                if let image = item.image {
    
                    //item.image = image.withRenderingMode(.alwaysTemplate)
    
                    item.image = image.withRenderingMode(.alwaysOriginal) //Use default image colour as grey colour and your centre image default colour as white colour as your requirement.
                }
            }
    
             //Change the backgound colour of specific tabBarItem.
    
             let itemIndex:CGFloat = 2.0
    
             let bgColor = UIColor.black
             let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
             let bgView = UIView(frame: CGRect.init(x: itemWidth * itemIndex, y: 0, width: itemWidth, height: tabBar.frame.height))
            bgView.backgroundColor = bgColor
            tabBar.insertSubview(bgView, at: 0)
    
        }
    
        // MARK: - UITabbarController Override Methods .
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    
        }
    
    
        // MARK: - UITabBarControllerDelegate Methods
        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
            return true
        }
    }
    

    根据您的 UI 使用 tabBarItem 图像默认颜色为灰色,并在资源中将 tabBarItem 图像默认颜色居中设置为白色。

    你会想要扩展 UIImage 类来制作你需要大小的纯色图像:

    extension UIImage {
        func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            color.setFill()
            UIRectFill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image!
        }
    }
    

    【讨论】:

    • 谢谢你..我已经在这里完成了这个答案:stackoverflow.com/a/31680820/4033273。此答案适用于选定的标签栏项目
    • 所以这种方法不适合你,如果不能,请在你使用上述代码的地方显示你的代码
    • @Moin Shirazi 检查更新的答案。
    • @Moin Shirazi 检查更新的答案是否仅将中心 UITabBarItem 实现为黑色。
    【解决方案3】:

    试试这个:

     UITabBar.appearance().tintColor = UIColor.pink
     UITabBar.appearance().barTintColor = UIColor.white
                if #available(iOS 10.0, *) {
                    UITabBar.appearance().unselectedItemTintColor = UIColor.white
                } else {
                    // Fallback on earlier versions
                }
    let x = Double(UIScreen.main.bounds.width / 5.0)
    let y = Double(tabBarController!.tabBar.frame.size.height)
    let indicatorBackground: UIImage? = self.image(from: UIColor.black, for: CGSize(width: x, height: y))
    UITabBar.appearance().selectionIndicatorImage = indicatorBackground
    

    辅助方法

    func image(from color: UIColor, for size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        autoreleasepool {
            UIGraphicsBeginImageContext(rect.size)
        }
        let context: CGContext? = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    

    【讨论】:

      【解决方案4】:

      你可以给父tabBar添加一个子视图 然后您可以在子视图上设置背景颜色。 计算你的 tabBarItem 的偏移量和宽度,并在它下面插入 subView。

      let itemIndex = 2
      let bgColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0)
      
      let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
      let bgView = UIView(frame: CGRectMake(itemWidth * itemIndex, 0, itemWidth, tabBar.frame.height))
      bgView.backgroundColor = bgColor
      tabBar.insertSubview(bgView, atIndex: 0)
      

      【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多