Reputation: 65
Im developing an application with multiple UIViewControllers
containing UILabel components. Alot of UIViewControllers
have the same setup a title, subtitle, subtext and/or text. In every UIViewControllers
I kept changing the font-size, color and more variables so i wanted to use something like a style for all the UIView
components so all the changes effect all the components in all the ViewControllers.
I created custom UILabel
classes and linked it in my storyboards with the custom class that implementing default style. But it is not working properly.
class UICustomLabel: UILabel
{
override func layoutSubviews()
{
super.layoutSubviews()
self.font = UIFont(name: Style.FontNameDefault, size: Style.FontSizeDefault);
}
}
class UILabelTitle: UILabel
{
override func layoutSubviews()
{
super.layoutSubviews()
self.font = UIFont(name: Style.FontNameTitle, size: Style.FontSizeTitle);
}
}
Is there a better way to style all the UIView components through your whole app the same way?
Upvotes: 0
Views: 1245
Reputation: 8006
There is a built in way to achieve this - it is called UIAppearance
. This protocol is implemented by all system views. You can read more here
And a small example :
[[UILabel appearance] setTextColor:[UIColor whiteColor]];
[[UILabel appearanceWhenContainedIn:[MyCustomView class]] setTextColor:[UIColor blueColor]]
Sorry for example in Obj-C, this is also avaiable in Swift.
The first line sets the text color for all UILabels
to white. The second line makes the text color blue, but only if the UILabel
is a subview of a MyCustomView
. This way you can easily add exceptions from a general rule, if there are any.
Also, note that the effects will take effect for UILabels
added after running this code, so the best place for this is propably in the AppDelegate
.
Upvotes: 0
Reputation: 96
You can make an extension on UILabel
that provides a number of factory methods for all label types you need.
extension UILabel {
class func stl_titleLabel() -> UILabel {
let label = UILabel()
label.font = ...
return label
}
class func stl_commentLabel(frame: CGRect, color: UIColor) -> UILabel { // whatever arguments you need
let label = UILabel(frame)
label.font = ...
label.textColor = color
return label
}
}
There are can be some syntax errors in code since I'm not that good with swift, but i think you get the idea. I'm hoping it helps.
EDIT: Oops, I missed that you use storyboards. My solution would work if labels were created with code. Maybe there is a way to combine it with storyboards, but i don't know how.
Upvotes: 1
Reputation: 575
I find this libraries very useful:
It's like CSS for iOS.
But if you are looking for pure iOS solution, try to set your font properties in awakeFromNib
or in init
instead of layoutSubviews
. Also make sure that your IBOutlets
in ViewControllers have correct declarations (e.g. UITitleLabel
instead of UILabel
)
Upvotes: 0