Lifetime Email
Lifetime Email

Reputation: 53

Create a class of Colors

In my app, I have for example 5 available colors for different Task that user can choose between them anytime. I thought it would be good to have a class of color and I declare few colors inside the class that in any controller I can access to those colors as an Array. For example when I want to show the colors to pickup, I want them as an array. But I don't know how to do that? I create a class but in the init part, I don't know how to add colors

final class Colors {
    var color : [UIColor]

    init(color: [UIColor]) {

    }
}

Your help will be appreciated.

Upvotes: 1

Views: 894

Answers (3)

akaur
akaur

Reputation: 375

Option 1 - You can extend UIColor to list all of your colors and create an array:

extension UIColor {
    struct GoTimeThemes {
        static let firstColor = UIColor(red: 48.0/255.0, green: 35.0/255.0, blue: 174.0/255.0, alpha: 1.0)
        static let secondColor = UIColor(red: 83.0/255.0, green: 160.0/255.0, blue: 263.0/255.0, alpha: 1.0)
        static let thirdColor = UIColor(red: 146.0/255.0, green: 80.0/255.0, blue: 156.0/255.0, alpha: 1.0)

        static var allColors: [UIColor] {
        let colors = [firstColor, secondColor, thirdColor]
        return colors
        }
    }
}

And call your array like so

let colors = UIColor.GoTimeThemes.allColors

Option 2 - You can put your colors in an Enum that conforms to CaseIterable:

enum ThemeColors: CaseIterable {
    case firstTheme, secondTheme, thirdTheme

    var color: UIColor {
        switch self {
        case .firstTheme:
            return UIColor(red: 48.0/255.0, green: 35.0/255.0, blue: 174.0/255.0, alpha: 1.0)
        case .secondTheme:
            return UIColor(red: 83.0/255.0, green: 160.0/255.0, blue: 263.0/255.0, alpha: 1.0)
        case .thirdTheme:
            return UIColor(red: 146.0/255.0, green: 80.0/255.0, blue: 156.0/255.0, alpha: 1.0)
        }
    }
}

And call it with allCases to get a Collection:

ThemeColors.allcases //→ [firstTheme, secondTheme, thirdTheme]

Upvotes: 3

Caleb
Caleb

Reputation: 124997

I thought it would be good to have a class of color and I declare few colors inside the class that in any controller I can access to those colors as an Array.

An enumeration would work well for this. The set of colors is fixed, right? It sounds like you won't need distinct instances of the set of colors, and it'd probably be nice to be able to access the colors without needing to create an object or bother with sharing an object. An enumeration gives you a set of discrete values, and it can have methods associated with it. For example, you could have a darkGreen value, and then methods like uiColor() and cgColor() that return UIColor and CGColor objects that correspond to that value.

Upvotes: 0

matt
matt

Reputation: 535140

Extend UIColor, make your colors static properties, and make your array a computed static property.

Upvotes: 4

Related Questions