iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

前端 未结 15 1470
有刺的猬
有刺的猬 2020-12-01 13:45

i want to change the button color when it is clicked. I used :

[button setBackgroundColor:[UIColor redColor]];

but this shows red color onl

15条回答
  •  不知归路
    2020-12-01 14:34

    Completing Dima answer, I've implemented an extension in Swift:

    extension UIButton {
        private func imageWithColor(color: UIColor) -> UIImage {
            let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()
    
            CGContextSetFillColorWithColor(context, color.CGColor)
            CGContextFillRect(context, rect)
    
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return image
        }
    
        func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
            self.setBackgroundImage(imageWithColor(color), forState: state)
        }
    }
    

提交回复
热议问题