【发布时间】:2011-11-01 15:16:07
【问题描述】:
当uibarbuttonitem被选中并突出显示时,我们可以改变它的颜色/色调吗?我正在创建的应用程序将经常在户外使用,并希望它在高眩光情况下更加引人注目,以便用户知道他实际上按下了按钮。
编辑:我想更改按钮突出显示状态的颜色
【问题讨论】:
标签: iphone objective-c uibarbuttonitem
当uibarbuttonitem被选中并突出显示时,我们可以改变它的颜色/色调吗?我正在创建的应用程序将经常在户外使用,并希望它在高眩光情况下更加引人注目,以便用户知道他实际上按下了按钮。
编辑:我想更改按钮突出显示状态的颜色
【问题讨论】:
标签: iphone objective-c uibarbuttonitem
您可以继承 UIBarButtonItem 并将 UIButton 放入其中,并为不同的状态使用不同的背景图像颜色。
- (id)initWithImage:(UIImage *)image target:(id)target action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = (CGRect){CGPointZero, image.size};
[button setBackgroundImage:image forState:UIControlStateNormal];
UIImage *highlightedImage = [image imageWithColor:[UIColor textHighlightColor]];
[button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
[button setBackgroundImage:highlightedImage forState:UIControlStateSelected];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
self = [self initWithCustomView:button];
return self;
}
你需要把它放到 UIImage 类别中:
- (UIImage *)imageWithColor:(UIColor *)color
{
// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(self.size);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextDrawImage(context, rect, self.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, self.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
【讨论】:
我没有尝试过,但是您可以尝试继承 UIBarButtonItem,然后覆盖 touchesEnded:withEvent: 和 touchesBegan:withEvent: 方法,然后使用它们为您的 UIBarButtonItem 实例设置 tintColor。
您可以将此添加到您的 UIBarButtonItem 子类中:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.tintColor = [UIColor redColor];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
self.tintColor = [UIColor blueColor];
}
【讨论】:
touchesEnded:withEvent:...?
UIButton 是 UIControl 的子类,它具有 adjustsImageWhenHighlighted、showTouchWhenHighlighted 和 showsTouchWhenHighlighted 属性。
UIBarButtonItem 是 UIBarItem 的子类,并且没有这些。但是,它确实有一个 UIBarButtonItemStyle ,当它设置为 UIBarButtonItemStylePlain 时,它表示按钮在点击时会发光(但您不能指定颜色)。
【讨论】: