如何以编程方式制作倒置颜色的uibutton?

时间:2014-01-01 10:55:25

标签: colors ios7 uibutton

iOS 7已经出现了一段时间了。我尝试做但未成功的一件事是将Apple内置的App按钮复制到他们的App Store应用程序中。

按钮具有1个像素边框,并在突出显示或选中时反转颜色。

我可以制作边框但无法以编程方式反转颜色效果而没有任何图像。

enter image description here enter image description here

我搜索了互联网,但到目前为止找不到任何有用的东西。

有没有人知道如何在iOS 7上为UIButton制作这种效果?

提前致谢

2 个答案:

答案 0 :(得分:2)

这就是我所拥有的:

#import <QuartzCore/QuartzCore.h>

+ (void)setCornerRadius:(CGFloat)radius ofView:(UIView*)view
{
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
}

+ (void)setBorderWidth:(CGFloat)width ofView:(UIView*)view
{
    view.layer.borderWidth = width;
}

+ (void)setBorderColor:(UIColor*)color ofView:(UIView*)view
{
    view.layer.borderColor = [color CGColor];
}

+ (void)styleButton:(UIButton*)button
{
    [Common setBorderWidth:1  ofView:button];
    [Common setCornerRadius:5 ofView:button];

    [Common setBorderColor:[UIColor blueColor] ofView:button];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];

    UIGraphicsBeginImageContextWithOptions(button.frame.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor blueColor] setFill];
    CGContextFillRect(context, CGRectMake(0, 0, button.frame.size.width, button.frame.size.height));
    UIImage*     image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [button setBackgroundImage:image forState:UIControlStateHighlighted];
}

请注意,这仅适用于UIButtonTypeCustom按钮。

当然,如果您在应用中使用其他tintColor,请替换[UIColor blueColor]

答案 1 :(得分:2)

当按钮处于“已选择”状态时,您可以在IOS中免费获得此功能。

您需要为按钮的touchUpInside Action创建一个例程。在该例程中,您必须切换“selected”属性。

- (IBAction)touchedFreeButton:(UIButton *)sender {
    self.freeButton.selected = !self.freeButton.selected;
}