绘制UIButton / UIBarButtonItem以使用父栏的tintColor?

时间:2012-12-14 22:10:04

标签: ios cocoa-touch uikit core-graphics uibarbuttonitem

我有点进退两难。这不是一个破坏者,但如果有的话,我对一个体面的答案很感兴趣。

我一直在UIButton内使用UIBarButtonItem自定义子视图(作为条形按钮项目的customView)。我的自定义子视图一个UILabel也不是UIImage,这就是为什么我正在做我正在做的事情。此UIBarButtonItem是导航栏上的项目,导航栏中设置了tintColor。我希望UIButton具有UIBarButtonItemStyleBordered的圆角直观外观,这意味着它还应该采用其父栏的tintColor

当前的解决方案已经实现了从UIKit中为png和家庭提取UINavigationBarDefaultButton.png文件。如果我没有设置tintColor属性,这将看起来很好;相反,按钮仍然是“iOS海军蓝”,当我想要,比方说,明亮的橙色(不是我使用的颜色,但你得到我的漂移)。这让我陷入困境:什么是使UIButton外观和行为像UIBarButtonItem样式,包括接受tintColor属性的最佳方式?我可以在按钮上设置该属性;这没什么大不了的。

我想在CoreGraphics中绘制UIButton的背景吗?是否有一个框架/库已经实现了这一点?如果我梦想不可能,请告诉我。我手动使用CoreGraphics并不是那么棒,但它绝对不会超出可能性范围。

如果无法做到这一点,我知道我总是可以采取很酷的自定义UIView我正在试图将其作为图像保存(并在其中使用UIImage一个UIBarButtonItem),但我想看看这是否可能。

这就是我正在处理的事情(下文)。后退按钮看起来很棒,但只是因为我没有弄乱它。我希望rightBarButtonItem使用我设置的tintColor,但是为了给UIBarButtonItemStyleBordered外观设置customView,我被迫使按钮使用png文件作为其背景。以下是您看到的内容,即使在tintColor上设置UIBarButtonItem(因为它使用的是png)。

uinavigationbar

2 个答案:

答案 0 :(得分:1)

我确实在Stack Overflow上找到了this question/answer,这让我足够接近我可以完成剩下的工作。这是一篇关于如何使用UIImageUIColor着色的详细信息。我已将其删除为一个函数,我已经为right here发布了一个要点。

结合这一点,我在UIButton上定义了一个类别方法,可以让我创建一个带有背景图像的按钮,并将其打印成空UIBarButtonItem

+ (id)buttonWithBarStyleAndTintColor:(UIColor *)tintColor customView:(UIView *)customView {
    UIImage *defaultNormal = [UIImage imageNamed:@"UINavigationBarDefaultButton.png"];
    UIImage *defaultPressed = [UIImage imageNamed:@"UINavigationBarDefaultButtonPressed.png"];
    UIImage *back = [TintImageWithTintColor(defaultNormal, tintColor)
                     stretchableImageWithLeftCapWidth:5.0
                     topCapHeight:0.0];
    UIImage *pressed = [TintImageWithTintColor(defaultPressed, tintColor)
                        stretchableImageWithLeftCapWidth:5.0
                        topCapHeight:0.0];

    UIButton *button = [self buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 34.0f, 30.0f);
    [button addSubview:customView];
    customView.userInteractionEnabled = NO;
    customView.frame = CGRectCenterRectInRect(customView.frame, button.frame);
    [button setBackgroundImage:back forState:UIControlStateNormal];
    [button setBackgroundImage:pressed forState:UIControlStateSelected];
    [button setBackgroundImage:pressed forState:UIControlStateHighlighted];
    return button;
}

答案 1 :(得分:0)

您可以尝试将UIButton类型设置为自定义,并确保其颜色清晰,与自定义视图相同,这样唯一可见的视图将是UIBarButtonItem色调。

此外,如果您愿意投资,还有一个名为PaintCode的工具可以为您完成CoreGraphics的代码。