Set background color of active tab bar item in Swift

前端 未结 3 684
刺人心
刺人心 2020-12-07 23:13

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

3条回答
  •  攒了一身酷
    2020-12-08 00:00

    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
    

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

    I hope this helps!

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

提交回复
热议问题