Xcode UITabBarItem选项卡栏项单个选定背景色

Xcode UITabBarItem选项卡栏项单个选定背景色,xcode,swift,uitabbarcontroller,swift2,xcode7,Xcode,Swift,Uitabbarcontroller,Swift2,Xcode7,在我的项目中,我使用UIImage的扩展创建并更改选项卡栏项目的选定背景色: extension UIImage { func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() as CGContextR

在我的项目中,我使用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
}   
}
然后在我的主控制器中使用它

 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.
}
这是可行的,但如何更改单个选项卡栏项目的选定背景色

如何更改单个选项卡栏项目的选定背景色


选项卡栏项目没有“选定的背景色”。他们所拥有的,您可以设置的是一个
选择的图像
。通过将其设置为渲染模式为
.AlwaysOriginal
的图像,您可以在选择时指定整个选项卡栏项目图像的外观,而不是未选择时的外观。

将其添加到应用程序: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;
}

我找到了无需添加其他图像的解决方法

类tabbar控制器:uitabbar控制器{
重写func viewDidLoad(){
super.viewDidLoad()
//更新第一项
dispatch\u async(dispatch\u get\u main\u queue()){
self.setSelection(self.tabBar.selectedItem!)
}
}
//标记:-UITabBarDelegate处理程序
覆盖功能选项卡栏(选项卡栏:UITabBar,didSelectItem项:uitabaritem){
选举()
选举(项目)
}
//标记:-选择方法
功能设置选择(项目:UITABBARIEM){
dispatch\u async(dispatch\u get\u main\u queue()){

对于0中的i..我为您提供了最完美、最简单的方法(只是开玩笑)。您可以将选项卡栏在AppDelegate中的外观设置为默认值,如下所示:

    let screenWidth = UIScreen.main.bounds.width
    let tabSelectedBGImage = R.image.tabSelectedBg()?.resize(toWidth: screenWidth/3)
    UITabBar.appearance().selectionIndicatorImage = tabSelectedBGImage
我必须将图像调整到正确的宽度,因为我有3个标签,我当然需要将屏幕宽度分为3。如果你不这样做,图像将无法填充标签项目的宽度。我将在我的博客上发布此消息:D


一个好方法是使用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

}
我找到的最简单的方法

Swift4

斯威夫特5

class SceneDelegate:UIResponder,UIWindowSceneDelegate{
变量窗口:UIWindow?
func场景(场景:UIScene,willConnectTo会话:UISceneSession,选项connectionOptions:UIScene.connectionOptions){
让imageTabSelected=UIImage(名为:“我的兄弟”)
UITabBar.appearance().selectionIndicatorImage=imageTabSelected
}
}
}

See,我使用
uitabar.appearance()。选择indicatorimage=UIImage()。使用颜色和大小生成图像(UIColor(红色:21/255.0,绿色:21/255.0,蓝色:21/255.0,alpha:1.0),大小:CGSizeMake(tabBar.frame.width/4,tabBar.frame.height))
为所有项目设置选定的背景图像,但如何单独设置?请不要问两次问题。你所做的只是让我给出两次相同的答案。这没有任何意义。
selectionIndicatorImage
是整个选项卡栏的属性,而不是单个选项卡栏项目的属性。我已经向你解释过了u您可以对单个选项卡栏项执行哪些操作。我说过您可以执行哪些操作。我已经回答了问题。什么是'R.image.tabSelectedBg()“嘿,这只是一个调整到一定宽度的UIImage。我意识到,这个答案并不完美。当它在iphone6和更大的屏幕上运行时,BG图像和屏幕的前导和尾随之间有一个非常小的间隙。在模拟器上,这很好,但当我在真实设备上运行它时,它在这里崩溃了。”(self.tabBar.selectedItem!),所选项目的值为零
1.choose selectionIndicationImage.
2.Set tabar clipstobounds = true
3.Set insets for image.
4.Enjoy