【问题标题】:How to change background of specific UITabBarItem [closed]如何更改特定 UITabBarItem 的背景 [关闭]
【发布时间】:2016-08-30 00:41:39
【问题描述】:

如何只更改 UITabBar 中一个选项卡按钮的背景颜色?我想重新创建 Instragram 的旧标签栏设计 (pictured on top),其中中间的“发布图片”标签具有不同的背景颜色。

接下来,有没有办法让颜色显示为图标周围的圆形?或者到那时我是否必须使用模拟作为标签栏的自定义工具栏?

【问题讨论】:

  • 可以使用Tabbar的selected image属性来设置选中图片

标签: ios swift swift2 uitabbar uitabbaritem


【解决方案1】:
    let count = CGFloat(tabBar.items!.count)
    let itemSize = CGSize(width: tabBar.frame.size.width / count, height: tabBar.frame.height)

    for (index, _) in tabBar.items!.enumerate() {
      if index == 2 {
        let xPosition = itemSize.width * CGFloat(index)
        let backgroundColor = UIView.init(frame: CGRect.init(x: xPosition, y: 0, width: itemSize.width, height: itemSize.height))
        backgroundColor.backgroundColor = UIColor.redColor()
        tabBar.insertSubview(backgroundColor, atIndex: 1)
      }
    }

我不久前实现了类似的效果,上面的代码是关键部分。

更新1:

如果您还想更改特定 tabBarItem 的选定背景颜色,下面的代码将完成这项工作。您需要继承 UITabBarController 并覆盖方法 tabBar:didSelectItem

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
  let index: Int = tabBar.items!.indexOf(item)!
  if index == 2 {
    tabBar.selectionIndicatorImage = UIImage.fromColor(UIColor.greenColor(), size: CGSize.init(width: UIScreen.mainScreen().bounds.size.width/5, height: 49))
  } else {
    tabBar.selectionIndicatorImage = UIImage.fromColor(UIColor.snpPaleblueColor(), size: CGSize.init(width: UIScreen.mainScreen().bounds.size.width/5, height: 49))
  }
  tabBar.setNeedsDisplay()
}

static func fromColor(color: UIColor, size: CGSize) -> UIImage {
  let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  UIGraphicsBeginImageContext(rect.size)
  let context = UIGraphicsGetCurrentContext()
  CGContextSetFillColorWithColor(context, color.CGColor)
  CGContextFillRect(context, rect)
  let img = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return img
}

更新2:

如果你想改变一个tabBarItem的图片和selectedImage颜色,使用UIImage的方法imageWithRenderingMode:例子如下。

item.image = UIImage.init(named: "tabBarIcon-white").imageWithRenderingMode(.AlwaysOriginal)
item.selectedImage = UIImage.init(named: "tabBarIcon-blue").imageWithRenderingMode(.AlwaysOriginal)

【讨论】:

  • 我能不能把中间按钮的颜色从self.tabBar.tintColor = UIColor(red: 0/255, green: 150/255, blue: 175/255, alpha: 1.0)改成UIwhiteColor
  • 我更新了答案,请看。
  • 嗨,谢谢你的回答,但你错过了理解我。我说的是改变图标的​​颜色。在上面的示例中,标签栏中的所有图标都是白色的。我想问如何将一个特定的(如中间的)设置为与其他图标不同的颜色?
  • 我更新了答案,请看一下。
  • 我不确定R 来自哪里,我得到“标识符 R 的未解决使用”
猜你喜欢
  • 2013-07-22
  • 1970-01-01
  • 2019-04-29
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多