【问题标题】:How to make inverted color uibutton programmatically?如何以编程方式制作反色uibutton?
【发布时间】:2014-01-01 10:55:25
【问题描述】:

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

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

我可以制作边框,但无法在没有任何图像的情况下以编程方式制作反色效果

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

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

提前致谢

【问题讨论】:

    标签: colors ios7 uibutton


    【解决方案1】:

    这是我得到的:

    #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]

    【讨论】:

    • 我最终继承了 UIButton 并以完全相同的方式实现。我也为 UIControlStateNormal 设置了背景图像。
    • 我投了反对票,因为 LevinsonTechnologies 应该是正确的答案。我已经对其进行了测试,并且可以正常工作。这显然是打算这样做的方式。
    【解决方案2】:

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

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

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

    【讨论】:

    • 你知道如何避免这种行为吗?我只想在不改变颜色的情况下使用不同的图像。
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2016-09-28
    相关资源
    最近更新 更多