Skip to content

Commit

Permalink
🎨 Update hexString init
Browse files Browse the repository at this point in the history
scanLocation and scanHexInt32 are deprecated from iOS 13.0
  • Loading branch information
Martin Svoboda authored and Martin Svoboda committed Nov 2, 2023
1 parent 359ff2b commit 7b3f4f4
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions ACKategories-iOS/UIColorExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,38 @@ public extension UIColor {
}

/**
Initialize color from hex string (eg. "#ff00ff"). Leading '#' is mandatory.
Initialize color from hex string (eg. "#ff00ff"). Leading '#' is not mandatory.

- parameter hexString: Hex string to create color from
*/
convenience init(hexString: String) {
var rgbValue: UInt32 = 0
let scanner = Scanner(string: hexString)
scanner.scanLocation = 1 // bypass '#' character
scanner.scanHexInt32(&rgbValue)
self.init(hex: rgbValue)
}
convenience init(hexString: String) {
var hexSanitized = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")

var rgb: UInt64 = 0

var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
let a: CGFloat = 1.0

let length = hexSanitized.count

guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else {
self.init()
return
}

if length == 6 {
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
b = CGFloat(rgb & 0x0000FF) / 255.0
} else {
self.init()
}

self.init(red: r, green: g, blue: b, alpha: a)
}

/**
Returns color as hex string (eg. '#ff00ff') or nil if RGBA components couldn't be loaded.
Expand Down

0 comments on commit 7b3f4f4

Please sign in to comment.