Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method for changing the String color "rgba(255, 255, 255, 1)" to a Swift color is:

  1. Remove the "rgba" and parentheses from the string, leaving only the numbers and commas.
  2. Split the remaining string by commas to separate the Red, Green, Blue, and Alpha values into an array.
  3. Convert each value in the array from a string to a CGFloat.
  4. Create a new UIColor object using the converted values.

Here's the Swift code to accomplish this:

let colorString = "rgba(255, 255, 255, 1)"
let componentsString = colorString.replacingOccurrences(of: "rgba(", with: "").replacingOccurrences(of: ")", with: "")
let componentsArray = componentsString.components(separatedBy: ",").map { CGFloat(Float($0.trimmingCharacters(in: .whitespacesAndNewlines))!/255.0) }
let color = UIColor(red: componentsArray[0], green: componentsArray[1], blue: componentsArray[2], alpha: componentsArray[3])

The resulting color object will be a Swift UIColor with the same RGBA values as the original string.