← back to the blog

SwiftUI use RGB for text. How to add custom RGB colours UIColor/ Color / .foregroundColor

Posted on December 15th, 2019 in Swift by George


Here is a short tutorial on how to use generic/conventional RGB color values with SwiftUI Swift 5.1


RGB values for UIColor are between 0 and 1 (see the documentation "specified as a value from 0.0 to 1.0")

You need to divide your numbers by 255.


1. For the sake of efficiency extend the UIColor class init method to take CGFload values.

extension UIColor {
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)


2. Initialize the color with the conventional RGB values.


let appBlue = UIColor(r: 0, g: 142, b: 207)


3. Declare the text field and apply the new color.

The foregroundColor method is used to set the color.


//Here Color takes as an argument UIColor defined above 

TextField("Please don't stop the music", text: $reg).foregroundColor(Color(appBlue))


Thank you!