I just wanted to know why there are two ways to obtain color in iOS. I am new to Swift and Objective C development, I just want to know how and why they are different?
Asked
Active
Viewed 741 times
1 Answers
6
CGColor
comes from a lower level than UIColor
. This difference is not so obvious in Swift anymore, but you may see this in Objective-C where UIColor
is an Objective-C class with methods while CGColor
is a C type and you access it with C functions.
UIColor
is part of the UIKit which is based on Core Graphics, where CGColor
belongs to. While UIKit is for iOS (and tvOS), Core Graphics is for macOS and iOS, and you may share code for Core Graphics between both.
Roughly speaking, Core Graphics is for drawing while UIKit and its macOS pendant AppKit are for GUI display.

clemens
- 16,716
- 11
- 50
- 65
-
Note - `UIColor` is for iOS, tvOS, and watchOS. `CGColor` is for all of those plus macOS. – rmaddy Feb 09 '18 at 06:38
-
@rmaddy: Yes, you're right. I've restricted to iOS because it's the focus here. – clemens Feb 09 '18 at 06:44
-
And UIKit is used for iOS, tvOS, and watchOS. – rmaddy Feb 09 '18 at 06:46
-
@rmaddy: I've updated my comment. ;) – clemens Feb 09 '18 at 06:47
-
CGColor is a C struct type. UIColor is an objective-c type. That's the difference. CGColor is used by low-level graphic library. `UIKit` just wrapped it in Objective-c for better iOS development experience. – AntiMoron Feb 09 '18 at 06:50
-
@clemens Yes, you use WatchKit for watchOS but WatchKit uses many UIKit classes. For example, `WKInterfaceButton` uses `UIColor` when setting the button's color. – rmaddy Feb 09 '18 at 06:53
-
@AntiMoron: This is what I meant with "while CGColor is a C type". – clemens Feb 09 '18 at 06:55
-
@rmaddy: Indeed, how unclean. – clemens Feb 09 '18 at 06:57