美文网首页
给UIButton设置不同状态下的背景色

给UIButton设置不同状态下的背景色

作者: 陈藩 | 来源:发表于2022-01-07 14:56 被阅读0次

    系统给出的UIButton设置背景是通过设置setImage和setBackgroundImage的方法,需要提供不同的图片素材。在开发中往往需要设置不同的纯色背景的button,而且往往没有图片。于是只好选择其他的方法了.以下的代码可以解决这个问题。

      extension UIButton {
          func setBackgroundColor(color: UIColor, forState: UIControl.State) {
                  self.clipsToBounds = true  // add this to maintain corner radius
                  UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            if let context = UIGraphicsGetCurrentContext() {
                    context.setFillColor(color.cgColor)
                    context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()
                    self.setBackgroundImage(colorImage, for: forState)
              }
        }  
    }
    

    相关文章

      网友评论

          本文标题:给UIButton设置不同状态下的背景色

          本文链接:https://www.haomeiwen.com/subject/pcpjcrtx.html