Search code examples
swiftuitableviewuicolorcgcolor

How to convert Color Literal to cgColor in the Swift?


var CodeBackground = #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1960784314, alpha: 1)

cells?.layer.borderColor = //... how can i set this color literal to cgColor?

As I know how to convert that UIColor to cgColor in the Swift

as example

UIColor.black.cgColor

Bingo, but what about Color Literal to cgColor in the Swift

Thank you.


Solution

    • As, You already know the simpler way of using colorLiteral as cgcolor, I'll jump to the other way of doing that...
    • For that you need a Custom Function which gets the color-value(red , green , blue) from the colorLiteral , which is as below

      extension UIColor {
          func rgb() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
          var fRed : CGFloat = 0
          var fGreen : CGFloat = 0
          var fBlue : CGFloat = 0
          var fAlpha: CGFloat = 0
          if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
              let iRed = Int(fRed * 255.0)
              let iGreen = Int(fGreen * 255.0)
              let iBlue = Int(fBlue * 255.0)
              let iAlpha = Int(fAlpha)
      
              _ = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
              return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
          } else {
              // Could not extract RGBA components:
              return nil
          }
      }
      }
      //It's more convenient to use function in `UIColor` extension
      
    • Now , after this function created you can convert colorliteral into cgColor as below...

      let CodeBackground = #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1960784314, alpha: 1)
      let rgblit = CodeBackground.rgb()
      let Converted_cgColor = CGColor(srgbRed: CGFloat(integerLiteral: rgblit!.red), green: CGFloat(integerLiteral: rgblit!.green), blue: CGFloat(integerLiteral: rgblit!.blue), alpha: CGFloat(integerLiteral: rgblit!.alpha))
      
    • You can directly use Converted_cgColor like

      cells?.layer.borderColor = Converted_cgColor
      

    HOPE IT HELPS