You can create new SwiftUI color with an extension of Color.
The extension does not need to be in a new Swift file, but it keeps your code clean to collect all Color extensions in one file.
Method 1: Use the RGB initializer:
(this is what OP was asking)
extension Color {
public static let myNewSwiftUIColor = Color(red: 219.0 / 255.0, green: 175.0 / 255.0, blue: 15.0 / 255.0, opacity: 1)
}
- Parameter
opacity replaces alpha
- No need to call
UIColor initializer
- Use
let, not var.
Method 2: Use XCode Color Set:
(others have answered, but incomplete or problematic)
extension Color {
public static let myNewSwiftUIColor = Color("myNewSwiftUIColor")
}
Use new color in your code:
Text("Example")
.foregroundcolor(Color.myNewSwiftUIColor)
Hint 1:
I had been wondering how to choose a color in a Color Set in Assets.
For those who didn't find this yet:
- In
Assets.xcassets, click on the Plus icon to add a Color Set.
- Give it a name by double clicking newly created color set 'Color' in the asset list. This will be the name string you have to provide in
extension Color. E.g. myNewSwiftUIColor
- Click on one of the white color pads (Any Appearance / Dark Appearance).
- Then in the right column of XCode, click on the gauge icon to show Attributes Inspector.
- Make your color choice from the well known picker GUI ;-)
Seems simple once you know it.
Hint 2:
As with all definitions, you can give a inline documentation that will show up in many places in XCode, e.g. Quick Help.
/// Like Color.green with a tad more yellow
/// - Note: Customized from Color 'Spring' from pallette 'Crayons'
public static let crayonOffSpring = Color("crayonOffSpring") }
I have found this helpful especially with colors, as to remember what it's for or where it came from.