6rfitq
Last Updated: February 25, 2016
·
11.39K
· itseranga
892414 10151468467596730 1847316210 o

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

Say Thanks
Respond