Reputation: 159
I'm developing a game and want to create a config for easy app skinning.
I'm stuck with device specific constants. For example I want to store device-specific font size. Lets say I want 30 for iPhone and 45 for iPad. Now I do it by declaring global variable like so:
let h2FontSize : CGFloat = UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 45 : 30
Then use it like so:
private let topLabel = CCLabelTTF(string: "", fontName: mainFontName, fontSize: h2FontSize)
But that is not seem like a beautiful solution, because I also have h1, h3 fontSize and they all look the same.
let h1FontSize : CGFloat = UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 60 : 45
let h2FontSize : CGFloat = UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 45 : 30
let h3FontSize : CGFloat = UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 30 : 15
How to deal with device-specific constants?
Upvotes: 1
Views: 92
Reputation: 2600
You can do something like:
private extension UIDevice {
static func isIpad() -> Bool {
return currentDevice().userInterfaceIdiom == .Pad
}
}
struct Font {
struct Size {
static let H1: CGFloat = UIDevice.isIpad() ? 60 : 45
static let H2: CGFloat = UIDevice.isIpad() ? 45 : 30
static let H3: CGFloat = UIDevice.isIpad() ? 30 : 15
}
}
Then, all your Font styling can be made directly in that Font struct. So if you need more styling you could make H1 return a styled UIFont with your needs instead of just a CGFloat which would decouple your styles even more.
Then, you can improve this by creating a Style struct that takes a UIDevice as a dependency instead of using the currentDevice() singleton.
Upvotes: 0
Reputation: 124997
How to deal with device-specific constants?
Make them part of your data model. These values aren't really constants -- they might not change after you set them up, but they're configured during execution and they depend on the particulars of the environment in which the app is running. So treat them like any other data in your app and put them in your data model.
Upvotes: 1