如何将UIAppearance Proxy属性应用于UILabel?

30

我试图将UIAppearance代理样式应用到UILabel类代理时,发现结果不可靠。例如,以下内容按照我的预期起作用:

[[UILabel appearance] setFont:[UIFont fontWithName:SOME_FONT size:SOME_SIZE]];
[[UILabel appearance] setShadowColor:[UIColor blackColor]];

设置文本颜色不起作用,但是这样做可以:

[[UILabel appearance] setColor:[UIColor greenColor]];

确实可行。有点不太可靠,并且会导致任何特定于实例的setTextColor:调用被忽略。

如何正确地将UIAppearance样式应用于UILabel?

4个回答

56

好的,事实证明你无法使用UIAppearance代理来样式化任何UILabel属性。

虽然UILabel类符合UIAppearanceContainer协议,但检查UILabel.h显示它的属性没有一个被标记为UI_APPEARANCE_SELECTOR,这是使用UIAppearance的先决条件。

糟糕。


2
这对我来说仍然令人费解。UIButton在UIAppearance下也完全无法自定义样式。我在2012年三月提出了一个问题反馈。我们只能希望他们在iOS 7中解决这个问题。 - rcw3
3
这太糟糕了!糟糕透了! - abbood
2
我不相信这仍然是真的。至少,在我的应用程序中,我能够使用UIAppearance代理来设置UILabel的样式。我遇到的问题是我不想要标签样式的区域,比如在UISegmentedControl内部。我尝试使用appearanceWhenContainedIn:来解决这个问题,但那很复杂,最终我放弃了外观代理并手动设置样式。 - mbm29414
1
是的,@Mojo66,它有点起作用了,请看我的原始问题 - 它不可靠,至少以前不是。 - Joshua J. McKinnon
1
在iOS11中仍然无法配置颜色,这是怎么回事还是有原因的?我无法相信苹果没有足够的人力来解决这个问题... - PakitoV
显示剩余2条评论

1
在Swift中,当UILabel包含在UITableViewHeaderFooterView中时,您需要执行以下操作来自定义外观属性:
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 18)
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).textColor = .white

这将适用于使用UITableViewHeaderFooterView时的textLabel属性:
 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
}

这在使用UITableViewStyle.grouped时非常有用,因为即使在viewForHeaderInSection中自定义UITableViewHeaderFooterView.textLabel,那些section header视图似乎仍会被覆盖为默认样式。

1
我已经对UILabel进行了子类化。
@interface SmallLabel : UILabel

@end

@implementation SmallLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

@end

然后我使用appearanceWhenContainedIn:

UIFont *smallFont = [UIFont fontWithName:@"Arial" size:15];
[[SmallLabel appearanceWhenContainedIn:[UIView class], nil] setFont:smallFont];

这个方法能够在我的应用程序中使用所需的字体来处理所有SmallLabel。我只需要在XCode Identity Inspector中将Custom Class设置为SmallLabel即可。这似乎不能与以编程方式创建的标签一起工作,仅适用于NIB中的标签。
经过进一步测试,这种方法并不总是可靠的。

0

以下代码适用于我使用的Swift 2.2和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`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接