iOS

    How to use hex color in Swift UI


    Introduction

    It uses hexadecimal because it's short, matching binary in a sense with its 4-bit-per-hex-digit resolution and is easier to read and write than the much longer numbers needed in binary. It is quite good for representing memory addresses, color codes, bitmasking, and compact debug forms for writing or reading into represent and manipulate data easily. We can extend the Color struct in SwiftUI with convenience methods to create colors from hex values.

    Examples

    extension Color { /// Initializes a Color from a hexadecimal string. /// Parameter hex: The hex string representing the color. init(hex: String) { var cleanHexCode = hex.trimmingCharacters(in: .whitespacesAndNewlines) cleanHexCode = cleanHexCode.replacingOccurrences(of: "#", with: "") var rgb: UInt64 Scanner(string: cleanHexCode).scanHexInt64(&rgb) let redValue = Double((rgb >> 16) & 0xFF) / 255.0 let greenValue = Double((rgb >> 8) & 0xFF) / 255.0 let blueValue = Double(rgb & 0xFF) / 255.0 self.init(red: redValue, green: greenValue, blue: blueValue) } }

     

    Let’s see how to use it:

    Text("Welcome to SWIFT UI") .font(.system(size: 16, weight: .regular)) .foregroundColor(Color(hex: "#222a80"))

     

    Ready to transform your business with our technology solutions? Contact Us  today to Leverage Our iOS Expertise.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    iOS

    Related Center Of Excellence