您的位置:首页 > 移动开发 > IOS开发

iOS 按钮点击改变背景色

2016-04-21 11:59 399 查看
- (void)viewDidLoad {

[super
viewDidLoad];

// Do any additional setup after loading the view.

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50,
50,
80, 40)];

btn.backgroundColor=
[UIColor colorWithRed:76/255.0 green:91/255.0blue:120/255.0 alpha:1];

[btn.layer setCornerRadius:3];

btn.layer.masksToBounds = YES;

[btn setTitle:@"button" forState:UIControlStateNormal];

[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

[btn setBackgroundImage:[self imageWithColor:
[UIColor colorWithRed:76/255.0green:91/255.0 blue:120/255.0 alpha:1]] forStat
e:UIControlStateNormal];

[btn setBackgroundImage:[self imageWithColor:
[UIColor colorWithRed:54/255.0green:65/255.0 blue:87/255.0 alpha:1]] forState
:UIControlStateHighlighted];

[self.view addSubview:btn];

}

// 颜色转换为背景图片

- (UIImage *)imageWithColor:(UIColor *)color {

CGRect rect = CGRectMake(0.0f,
0.0f, 1.0f,
1.0f);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context =
UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [color
CGColor]);

CGContextFillRect(context, rect);

UIImage *image =
UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: