在Swift中设置活动标签栏项目的背景颜色 [英] Set background color of active tab bar item in Swift

查看:76
本文介绍了在Swift中设置活动标签栏项目的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能的话,我希望在不使用图像的情况下完成此操作.有没有一种方法可以以编程方式创建图像中显示的效果,而不必将每个选项卡都呈现为图像?

I'm hoping to accomplish this without the use of images, if at all possible. Is there a way to create the effect shown in the image programmatically without have to render each tab out as an image?

我在SO上审查的每个问题都将选项卡另存为JPG,这比我想象的要多.

Every question I've reviewed on SO has the tabs saved as JPGs, which is more work than I feel it should be.

有什么想法吗?

推荐答案

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

I took a similar approach to @matcartmill but without the need for a special image. This solution is just based on your color.

// 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

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

I'm making use of the following extension of 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
    }

}

我希望这会有所帮助!

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
   }
}

这篇关于在Swift中设置活动标签栏项目的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆