30

在尝试将 UIAppearance 代理样式应用于 UILabel 类代理时,我得到了不可靠的结果。例如,以下工作如我所料:

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

设置 textColor 不起作用,但是,这个:

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

确实有效。那种。它有点不可靠,并导致任何特定于实例的调用setTextColor:被忽略。

将 UIAppearance 样式应用于 UILabel 的正确方法是什么?

4

4 回答 4

56

好的,事实证明您无法使用UIAppearance代理设置任何 UILabel 属性的样式。

虽然UILabel该类符合UIAppearanceContainer协议,但对 UILabel.h 的检查表明它的所有属性都没有标记UI_APPEARANCE_SELECTOR,这是使用的先决条件UIAppearance

臭虫。

于 2012-08-07T04:16:20.273 回答
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];

这可以为我的应用程序中的所有 SmallLabels 使用所需的字体。我只需要在 XCode 身份检查器中将自定义类设置为 SmallLabel。它似乎不适用于以编程方式创建的标签,仅适用于 NIB 中的标签。

经过进一步测试,这种方法并不总是可靠地工作。

于 2013-06-13T15:26:47.397 回答
1

在 Swift 中,您可以执行以下操作来自定义包含在 UITableViewHeaderFooterView 中的 UILabel 的外观属性:

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,这些节标题视图似乎也被默认样式覆盖

于 2017-08-15T18:39:32.443 回答
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`
于 2017-04-18T12:53:17.450 回答