How do you change UIButton image alpha on disabled state?

后端 未结 11 2232
庸人自扰
庸人自扰 2021-02-03 23:22

I have a UIButton with an image and on its disabled state, this image should have .3 alpha.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIIm         


        
11条回答
  •  天涯浪人
    2021-02-04 00:00

    You need two instances of UIImage, one for enabled and one for disabled.

    The tough part is for the disabled one, you can't set alpha on UIImage. You need to set it on UIImageView but button doesn't take an UIImageView, it takes a UIImage.

    If you really want to do this, you can load the same image into the disabled button state after creating a resultant image from the UIImageView that has the alpha set on it.

    UIImageView *uiv = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"];
    
    // get resultant UIImage from UIImageView
    UIGraphicsBeginImageContext(uiv.image.size);
    CGRect rect = CGRectMake(0, 0, uiv.image.size.width, uiv.image.size.height);
    [uiv.image drawInRect:rect blendMode:kCGBlendModeScreen alpha:0.2];  
    
    UIImage *disabledArrow = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();
    
    [button setImage:disabledArrow forState:UIControlStateDisabled];
    

    That's a lot to go through to get an alpha controlled button image. There might be an easier way but that's all I could find. Hope that helps.

提交回复
热议问题