众所周知,UIButton
只有在有背景图的时候,才有默认的按下效果
如果一个按钮只有背景色没有图片,按下是没有效果的。
解决思路就是能不能用颜色来生成一个图片呢。
下面直接上代码。
OC 代码
// 调用
[self.confirmButton setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
- (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;
}
Swift 代码
class BaseButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var backgroundColor: UIColor? {
didSet {
let backgroundColor = self.backgroundColor ?? UIColor.white
setBackgroundImage(generateMaskImage(from: backgroundColor), for: .normal)
}
}
private func generateMaskImage(from color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
网友评论