I have been getting unreliable results while trying to apply UIAppearance proxy styles to the UILabel class proxy. For example, the following works as I would expect:
<In Swift you do the following to customize the appearance attributes for a UILabel when contained in a UITableViewHeaderFooterView:
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 18)
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).textColor = .white
This will apply to the textLabel attribute when you use UITableViewHeaderFooterView in:
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerViewId)
if headerView == nil {
headerView = UITableViewHeaderFooterView(reuseIdentifier: headerViewId)
}
headerView?.textLabel?.text = "My Header".uppercased()
return headerView
}
This really helps when using the UITableViewStyle.grouped, as those section header views seem to be overridden with a default style even if you customize the UITableViewHeaderFooterView.textLabel in viewForHeaderInSection
I have subclassed UILabel
@interface SmallLabel : UILabel
@end
@implementation SmallLabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
@end
Then I use appearanceWhenContainedIn:
UIFont *smallFont = [UIFont fontWithName:@"Arial" size:15];
[[SmallLabel appearanceWhenContainedIn:[UIView class], nil] setFont:smallFont];
This works to use the desired font for all SmallLabels in my app. I just need to set the Custom Class to SmallLabel in the XCode Identity Inspector. It does not seem to work with labels create programmatically, only those in NIBs.
After further testing this method does not always work reliably.
OK, it turns out that you cannot style any UILabel properties using the UIAppearance
proxy.
While the UILabel
class conforms to the UIAppearanceContainer
protocol, a check of UILabel.h shows that none of its properties are marked with UI_APPEARANCE_SELECTOR
, the prerequisite for the use of UIAppearance
.
Bugger.
Following code worked for me using swift 2.2 and for iOS 9.0
let textFieldInsideSearchBar = self.searchBar?.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = BCGConstants.Colors.darkBluishPurpleColor()
let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor(red: 220/255, green: 209/255, blue: 231/255, alpha: 1.0)`enter code here`