iOS小技巧-自定义按钮设置颜色点击效果

在自定义按钮的时候,如果设置按钮的背景为颜色时,点击时就不会有系统自带的点击效果,下发的这个方法只需用一行代码就可以解决我们的需求,例子:

[button setBackgroundImage[self imageWithColor:[UIColor whiteColor]]  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;
}

你可能感兴趣的:(iOS小技巧-自定义按钮设置颜色点击效果)