【问题标题】:Change UITabBarController Tabs icons color when tab is not selected未选择选项卡时更改 UITabBarController 选项卡图标颜色
【发布时间】:2016-07-22 07:09:21
【问题描述】:

美好的一天, 我正在使用情节提要中的 UITabBarController,并且我想将图标颜色从默认的灰色更改为白色。

我在stackOverflow和其他网站上尝试了很多解决方案,但都没有用。

【问题讨论】:

标签: ios objective-c iphone swift2


【解决方案1】:

默认选项卡色调颜色:-

Obj-C 版本:-

[[self tabBar] setTintColor:[UIColor blackColor]];

Swift 2.2 版本:-

self.tabBar.tintColor = UIColor.whiteColor()

选定的选项卡色调颜色:-

Obj-C 版本:-

[[self tabBar] setSelectedImageTintColor:[UIColor blueColor]]; 

Swift2.2 版本:-

self.tabBar.selectedImageTintColor = UIColor.blueColor()

【讨论】:

  • Default tint color 的代码没有效果,第二个代码,对于选定的标签颜色,效果很好,但该功能已弃用
【解决方案2】:

我找到了使用这个循环的解决方案

for(UITabBarItem *item in self.tabBar.items) {
        // use the UIImage category code for the imageWithColor: method
        item.image = [[[item selectedImage] imageWithColor:[UIColor redColor]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];


    }

UITabBarController 类中。 并且应该添加包含方法imageWithColorUIImage+Overlay

- (UIImage *)imageWithColor:(UIColor *)color1
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    [color1 setFill];
    CGContextFillRect(context, rect);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

【讨论】:

    【解决方案3】:

    我从this link 找到了另一个解决方案。 不必使用循环。我修改了他的代码以删除警告

    makeImageWithColorAndSize 函数可以作为普通函数实现

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

    使用示例:

    override func viewWillAppear(animated: Bool) {
        self.tabBar.selectionIndicatorImage = UIImage().makeImageWithColorAndSize(
                  UIColor.blueColor(), 
                  size: CGSizeMake(tabBar.frame.width/5, tabBar.frame.height))
    
        super.viewWillAppear(animated)
    }
    

    Gwendle的原码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2013-11-25
      相关资源
      最近更新 更多