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

标签 ios cocoa-touch uikit core-graphics uibarbuttonitem

我现在有点进退两难。这不是一个破坏性的事情,但我对一个像样的答案感兴趣(如果有的话)。

我一直在 UIBarButtonItem 内使用带有自定义 subview 的 UIButton (作为栏按钮项的 customView)。我的自定义 subview 不是 UILabel 也不是 UIImage,这就是我正在做的事情的原因。这个UIBarButtonItem是我的导航栏上的一个项目,并且导航栏有一个tintColor集。我希望 UIButton 具有 UIBarButtonItemStyleBordered 的圆角矩形外观,这意味着它还应该采用其父栏的 tintColor

当前的解决方案已经实现了从 UIKit 中为 UINavigationBarDefaultButton.png 及其系列提取 png 文件。如果我没有设置 tintColor 属性,这看起来会很棒;相反,当我想要亮橙色(不是我正在使用的颜色,但你明白我的意思)时,按钮仍然是“iOS海军蓝”。这让我陷入了两难境地:让 UIButton 的外观和行为类似于 UIBarButtonItem 样式,包括采用 tintColor 属性的最佳方式是什么?我可以自己在按钮上设置该属性;没什么大不了的。

我想在 CoreGraphics 中绘制 UIButton 的背景吗?是否有一个框架/库已经实现了这一点?如果我正在梦想不可能的事,请告诉我。我还不太擅长手工制作 CoreGraphics,但这绝对不是不可能的。

如果这不能完成,我知道我总是可以采用我试图欺骗的很酷的自定义 UIView 并将其保存为图像(因此使用 UIImage 位于 UIBarButtonItem 内),但我想看看这是否可行。

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

uinavigationbar

最佳答案

我确实找到了this question/answer在 Stack Overflow 上,这让我足够接近,我可以为剩下的事情做准备。这是一篇关于如何使用 UIColorUIImage 进行着色的详细文章;我已将其提取到一个函数中,并为此发布了要点 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;
}

关于ios - 绘制 UIButton/UIBarButtonItem 以使用父栏的tintColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13886967/

相关文章:

ios - 无法打开文件 “***.app”,因为您没有查看它的权限

ios - 在 iOS 上的地址簿中获取图像联系人

ios - 找到一周中依赖于语言环境的第一天

swift - 如何从swift发送确认邮件

ios - 如何在选择时为 UICollectionViewCell 内容的扩展设置动画?

ios - 转换矩形 :toView doesn't return expected window coordinates

objective-c - 标签栏应用问题

ios - 更改 UISearchController 在 Swift 中的位置

ios - 以编程方式执行 segue 时没有动画

ios - 从 UITapGestureRecognizer 中排除 subview