其他分享
首页 > 其他分享> > UIButton按钮的高亮状态颜色

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)];
}

 

标签:高亮,button,borderWidth,UIButton,按钮,cornerRadius
来源: https://www.cnblogs.com/cchHers/p/12356004.html