Last Updated: September 29, 2021
·
22.34K
· itseranga

IOS UI colors with hex values in swfit

UIColorFromHex function

  • There is no any default function to define UI colors with hex values in IOS

  • Following swift function can be use to define colors with hex(RBG) values

func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
    let blue = CGFloat(rgbValue & 0xFF)/256.0

    return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}

// rbgValue - define hex color value
// alpha - define transparency value
// returns - CGColor

Function usage(set view background color)

var loadingView: UIView = UIView()
loadingView.frame = CGRectMake(0, 0, 80, 80)
loadingView.center = self.view.center

// set background color
loadingView.backgroundColor = UIColorFromHex(0x444444, alpha: 0.7)
  • Output would be like below

Picture

Function usage(set view border color)

  • When define border color of a view, need to convert UIColor to CGColor
var loadingView: UIView = UIView()
loadingView.frame = CGRectMake(0, 0, 80, 80)
loadingView.center = self.view.center

// set background color
loadingView.backgroundColor = UIColorFromHex(0x444444, alpha: 0.7)

// set border width and color
loadingView.layer.borderColor = UIColorFromHex(0xdf661d).CGColor
loadingView.layer.borderWidth = 2
  • Output would be like below

Picture

Related protips:

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

1 Response
Add your response

I think it's "/ 255.0" instead of "256.0"

over 1 year ago ·