UITabBarItem选项卡栏项目单个选定的背景颜色

时间:2015-11-04 01:13:23

标签: xcode swift uitabbarcontroller swift2 xcode7

在我的项目中,我使用UIImage的扩展来创建更改选项卡栏项目的选定背景颜色:

extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)

    let context = UIGraphicsGetCurrentContext() as CGContextRef!
    CGContextTranslateCTM(context, 0, self.size.height)
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, CGBlendMode.Normal)

    let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
    CGContextClipToMask(context, rect, self.CGImage)
    tintColor.setFill()
    CGContextFillRect(context, rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
    UIGraphicsEndImageContext()

    return newImage
}

func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(CGRectMake(0, 0, 100, 100))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}   
}

然后在我的MainTabBarController中使用它

 class MainTabBarController: UITabBarController {
 override func viewDidLoad() {
    super.viewDidLoad()

    let itemIndex = 0
    let bgColor = UIColor(red: 194/255.0, green: 39/255.0, blue: 65/255.0, alpha: 1.0)

    let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
    let frame = CGRectMake(CGFloat(itemWidth) * CGFloat(itemIndex), 0, itemWidth, tabBar.frame.height)
    let bgView = UIView(frame: frame)

    bgView.backgroundColor = bgColor
    tabBar.insertSubview(bgView, atIndex: 0)

    for item in self.tabBar.items as [UITabBarItem]! {
        if let image = item.image {
            item.image = image.imageWithColor(UIColor.whiteColor()).imageWithRenderingMode(.AlwaysOriginal)
        }


        // Sets the default color of the icon of the selected UITabBarItem and Title
        UITabBar.appearance().tintColor = UIColor.whiteColor()

        // Sets the default color of the background of the UITabBar
        UITabBar.appearance().barTintColor = UIColor(red: 39/255.0, green: 39/255.0, blue: 39/255.0, alpha: 1.0)

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


        print(UITabBar.appearance().selectionIndicatorImage)



        UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor(red: 21/255.0, green: 21/255.0, blue: 21/255.0, alpha: 1.0), size: CGSizeMake(tabBar.frame.width/4, tabBar.frame.height))

    }

    // Do any additional setup after loading the view.
}

这样可行,但如何更改单个标签栏项目的所选背景颜色?

7 个答案:

答案 0 :(得分:7)

将此添加到应用程序:didFinishLaunchingWithOptions:

UIColor *backgroundColor = [UIColor greenColor];

// set the bar background color
[[UITabBar appearance] setBackgroundImage:[AppDelegate imageFromColor:backgroundColor forSize:CGSizeMake(320, 49) withCornerRadius:0]];

// set the text color for selected state
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor, nil] forState:UIControlStateSelected];
// set the text color for unselected state
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor, nil] forState:UIControlStateNormal];

// set the selected icon color
[[UITabBar appearance] setTintColor:[UIColor whiteColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor whiteColor]];
// remove the shadow
[[UITabBar appearance] setShadowImage:nil];

// Set the dark color to selected tab (the dimmed background)
[[UITabBar appearance] setSelectionIndicatorImage:[AppDelegate imageFromColor:[UIColor colorWithRed:26/255.0 green:163/255.0 blue:133/255.0 alpha:1] forSize:CGSizeMake(64, 49) withCornerRadius:0]];

添加一个辅助函数将UIColor转换为UIImage

您可以将此代码放到AppDelegate或其他任何地方:

+ (UIImage *)imageFromColor:(UIColor *)color forSize:(CGSize)size withCornerRadius:(CGFloat)radius
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Begin a new image that will be the new image with the rounded corners
    // (here with the size of an UIImageView)
    UIGraphicsBeginImageContext(size);

    // Add a clip before drawing anything, in the shape of an rounded rect
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
    // Draw your image
    [image drawInRect:rect];

    // Get the image, here setting the UIImageView image
    image = UIGraphicsGetImageFromCurrentImageContext();

    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();

    return image;
}

答案 1 :(得分:3)

我找到了解决方法而没有添加其他图片

class TabBarController: UITabBarController {
override func viewDidLoad() {
    super.viewDidLoad()
    // update first item
    dispatch_async(dispatch_get_main_queue()) {
        self.setSelection(self.tabBar.selectedItem!)
    }
}

// MARK: - UITabBarDelegate handlers

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    clearSelections()
    setSelection(item)
}

// MARK: - Selection Methods

func setSelection(item:UITabBarItem) {
    dispatch_async(dispatch_get_main_queue()) {
        for i in 0..<self.tabBar.items!.count {
            let ii = self.tabBar.items![i]
            if(item == ii) {
                let sv = self.tabBar.subviews[i+1]
                let label:UILabel =  sv.subviews[1] as! UILabel
                print("didSelectItem \(label.text) = \(ii.title)")
                sv.backgroundColor = UIColor() // Selection color
            }
        }
    }
}

func clearSelections() {
    for s in tabBar.subviews {
        s.backgroundColor = UIColor.clearColor()
    }
}
}

结果我可以设置所选标签的背景颜色 enter image description here

答案 2 :(得分:2)

  

如何更改单个标签栏项目的选定背景颜色

标签栏项目没有选择的背景颜色&#34;。他们可以设置的内容是unsortedArray = [ {'Email': 'jen@test.com', 'Created': '1/15/14 15:01'}, {'Email': 'julia@test.com', 'Created': '1/16/14 18:21'}, {'Email': 'andy@test.com', 'Created': '1/15/14 22:41'}, {'Email': 'julia@test.com', 'Created': '1/16/14 18:20'}, {'Email': 'victoria@test.com', 'Created': '1/16/14 23:05'}, {'Email': 'lindsey@test.com', 'Created': '1/17/14 9:02'}, {'Email': 'jim@test.com', 'Created': '1/17/14 11:28'} ] 。通过将其设置为渲染模式为selectedImage的图像,您可以在选中时指示整个标签栏项目图像的外观,而不是在未选中时。“/ p>

答案 3 :(得分:0)

在 swift 5

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

          let imageTabSelected = UIImage(named: "my_bg")
          UITabBar.appearance().selectionIndicatorImage = imageTabSelected
        }
    }
}

答案 4 :(得分:-1)

我给你最完美最简单的方法(开玩笑)。您可以在AppDelegate中设置TabBar外观的 selectionIndicatorImage ,如下所示:

    let screenWidth = UIScreen.main.bounds.width
    let tabSelectedBGImage = R.image.tabSelectedBg()?.resize(toWidth: screenWidth/3)
    UITabBar.appearance().selectionIndicatorImage = tabSelectedBGImage

我必须将图像调整到正确的宽度,因为我有3个标签,我需要将screenWidth分成3个。如果不这样做,图像将不会填充标签项的宽度。 我在我的博客上发布此内容:D

enter image description here

答案 5 :(得分:-1)

一个好方法可能是使用AlamofireImage库并根据需要调整图像大小,然后在UITabBarViewController类的viewDidLoad方法中设置它:

 override func viewDidLoad() {
    super.viewDidLoad()

    let screenWidth = UIScreen.main.bounds.width
    let tabSelectedBGImage = UIImage(named:"tab_selector")
    let size = CGSize(width: screenWidth/5, height: (tabSelectedBGImage?.size.height)!)
    let aspectScaledToFitImage = tabSelectedBGImage?.af_imageAspectScaled(toFill: size)

    UITabBar.appearance().selectionIndicatorImage = aspectScaledToFitImage

}

答案 6 :(得分:-1)

我发现最简单的方式。

<强> Swift4 enter image description here

1.choose selectionIndicationImage.
2.Set tabar clipstobounds = true
3.Set insets for image.
4.Enjoy