Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uicolor hexcolor init #136

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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: "")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To achieve this kind of change you can simply use the original 5 line solution and only adjust scanLocation based on whether the string has leading hash or not.


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()
}

Comment on lines +27 to +48
Copy link

@babacros babacros Nov 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👋 Hey, I agree with @olejnjak. By the way, comments are missing...and what about correct indentation? Is it just copy&paste from Stack Overflow? In the case of using ChatGPT, I would ask to add comments 🤔

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
Loading