昨天想要设置UIButton的点击效果,查看之后发现要使用setImage来设置图片才行,但是我这里使用的是setbackColor来设置的纯色UIButton,所以没有点击效果,因此就想到要使用颜色值创建UIImage,通过查阅及实验,特将成果进行记录,代码如下:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, 100, 50)];
[btn setTitle:NSLocalizedString(@"xxx", @"") forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
// 使用颜色创建UIImage
CGSize imageSize = CGSizeMake(btn.frame.size.width, btn.frame.size.height);
UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
[[UIColor colorwithTSDefine:color_bg_11] set];
UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
UIImage *pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[btn setBackgroundImage:pressedColorImg forState:UIControlStateNormal];
btn.layer.cornerRadius = 5.0f;
btn.layer.masksToBounds = YES;
btn.opaque = NO;
[btn addTarget:self action:@selector(onHitBtn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
IOS使用颜色值创建UIImage
点赞
收藏