【发布时间】:2014-01-01 10:55:25
【问题描述】:
iOS 7 已经出现了一段时间。我尝试做但未成功的一件事是复制 Apple 内置到其 App Store 应用程序中的购买按钮。
按钮有 1 个像素的边框,并在突出显示或选中时反转颜色。
我可以制作边框,但无法在没有任何图像的情况下以编程方式制作反色效果。
我搜索了互联网,但到目前为止找不到任何有用的东西。
有人知道如何在 iOS 7 上为 UIButton 制作这种效果吗?
提前致谢
【问题讨论】:
iOS 7 已经出现了一段时间。我尝试做但未成功的一件事是复制 Apple 内置到其 App Store 应用程序中的购买按钮。
按钮有 1 个像素的边框,并在突出显示或选中时反转颜色。
我可以制作边框,但无法在没有任何图像的情况下以编程方式制作反色效果。
我搜索了互联网,但到目前为止找不到任何有用的东西。
有人知道如何在 iOS 7 上为 UIButton 制作这种效果吗?
提前致谢
【问题讨论】:
这是我得到的:
#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]。
【讨论】:
当按钮处于“选中”状态时,您可以在 IOS 中免费获得此功能。
您需要为按钮的 touchUpInside Action 创建例程。在该例程中,您必须切换“选定”属性。
- (IBAction)touchedFreeButton:(UIButton *)sender {
self.freeButton.selected = !self.freeButton.selected;
}
【讨论】: