在Swift中设置活动标签栏项目的背景颜色

mat*_*ill 21 uitabbar ios swift

如果可能的话,我希望在不使用图像的情况下实现这一目标.有没有办法以编程方式创建图像中显示的效果,而无需将每个标签渲染为图像?

我在SO上审查的每个问题都将选项卡保存为JPG,这比我应该做的更多.

有任何想法吗?标签栏

sch*_*ing 54

我对@matcartmill采用了类似的方法,但不需要特殊的图像.此解决方案仅基于您的颜色.

// set red as selected background color
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor.red, size: tabBarItemSize).resizableImage(withCapInsets: UIEdgeInsets.zero)

// remove default border
tabBar.frame.size.width = self.view.frame.width + 4
tabBar.frame.origin.x = -2
Run Code Online (Sandbox Code Playgroud)

我正在使用以下扩展名UIImage:

extension UIImage {

    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!

对于斯威夫特4

extension UIImage {

   class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 辉煌!我实际上只需要再次使用此方法,所以我回到了这篇文章。这显然是我所见过的最好方法。 (2认同)
  • 它不适用于iPhone 7s,但适用于iPhone 5s,为什么? (2认同)
  • @schickling,直到iOS 11 / xcode 9都很好。任何想法如何使其像iOS 11之前一样适合整个项目? (2认同)
  • 这在iPhoneX模拟器上无法正常工作 (2认同)
  • 在iPhone X中不起作用。设计崩溃 (2认同)

Kev*_*bbe 10

更新SWIFT 3:

let numberOfItems = CGFloat((tabBarController?.tabBar.items!.count)!)

let tabBarItemSize = CGSize(width: (tabBarController?.tabBar.frame.width)! / numberOfItems,
                            height: (tabBarController?.tabBar.frame.height)!)

tabBarController?.tabBar.selectionIndicatorImage
    = UIImage.imageWithColor(color: UIColor.black,
                             size: tabBarItemSize).resizableImage(withCapInsets: .zero)

tabBarController?.tabBar.frame.size.width = self.view.frame.width + 4
tabBarController?.tabBar.frame.origin.x = -2

extension UIImage
{
    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage
    {
        let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
Run Code Online (Sandbox Code Playgroud)