UIButton按钮的高亮状态颜色
首先是adjustsImageWhenHighlighted属性的正确使用:
UIButton的adjustsImageWhenHighlighted属性是当UIButton设置了背景图片时,并且没有设置高亮状态下的背景图片,点击按钮是否有高亮状态。
默认下是YES,也就是说当我们点击按钮的时候会有高亮状态,当我们设置button.adjustsImageWhenHighlighted = NO;时,再点击图片就看不到高亮状态了。
想取消按钮的高亮状态,可以继承UIButton自定义按钮控件,然后在实现文件中重写下面的方法:
// 重写系统setHighlighted方法,取消按钮点击高亮显示 - (void)setHighlighted:(BOOL)highlighted {}
也可以使用KVO,当按钮在高亮状态时可以进行处理,比如:
- (void)addObserver:(UIButton *)button { [button addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { UIButton *button = (UIButton *)object; if ([keyPath isEqualToString:@"highlighted"]) { if (button.highlighted) { [button setBackgroundColor:UIColorFromHEX(0xF8F8F8)]; return; } [button setBackgroundColor:UIColorFromHEX(0xFFFFFF)]; } }
设置按钮高亮状态下的颜色:
[control setBackgroundImage:[UIImage ctRoundRectImageWithFillColor:UIColorFromHEX(0xFAFAFA) cornerRadius:0] forState:UIControlStateHighlighted];
也可以使用上面这个方法,模拟出无高亮状态:
[control setBackgroundImage:[UIImage ctRoundRectImageWithFillColor:[UIColor clearColor] cornerRadius:0] forState:UIControlStateHighlighted];
上面用到的颜色转Image的方法为:
+ (UIImage *)ctRoundRectImageWithFillColor:(UIColor *)fillColor cornerRadius:(CGFloat)cornerRadius { return [self ctRoundRectImageWithFillColor:fillColor borderColor:nil borderWidth:0.0f cornerRadius:cornerRadius]; } + (UIImage *)ctRoundRectImageWithFillColor:(UIColor *)fillColor borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth cornerRadius:(CGFloat)cornerRadius { CGFloat halfBorderWidth = borderWidth * 0.5f; CGFloat w = cornerRadius + halfBorderWidth; CGFloat dw = w * 2 +2; UIGraphicsBeginImageContextWithOptions(CGSizeMake(dw, dw), NO, [UIScreen mainScreen].scale); CGContextRef context = UIGraphicsGetCurrentContext(); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(halfBorderWidth, halfBorderWidth, dw - borderWidth, dw - borderWidth) cornerRadius:cornerRadius]; [fillColor setFill]; [path fill]; if (borderWidth > 0.0f && borderColor) { [borderColor setStroke]; path.lineWidth = borderWidth; [path stroke]; } CGContextAddPath(context, path.CGPath); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return [image resizableImageWithCapInsets:UIEdgeInsetsMake(w+1, w+1, w+1, w+1)]; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了