标签:高亮 button borderWidth UIButton 按钮 cornerRadius
首先是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)]; }
标签:高亮,button,borderWidth,UIButton,按钮,cornerRadius 来源: https://www.cnblogs.com/cchHers/p/12356004.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。