iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

前端 未结 15 1427
有刺的猬
有刺的猬 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:24

    Thanks to @Dima

    Here is an updated code for swift 3.0 as UIButton extension

    extension UIButton {
      // thanks to @Dima http://stackoverflow.com/a/24665476/2581637 update code for swift 3
      func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        func imageWithColor(color: UIColor) -> UIImage? {
          let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
          UIGraphicsBeginImageContext(rect.size)
          if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(rect)
          }
    
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
    
          return image
        }
    
        self.setBackgroundImage(imageWithColor(color: color), for: state)
      }
    }
    

提交回复
热议问题