Подтвердить что ты не робот

Как применить свойства UIAppearance Proxy к UILabel?

Я получаю ненадежные результаты при попытке применить стили прокси-сервера 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?

4b9b3361

Ответ 1

ОК, оказывается, что не может создавать любые свойства UILabel с помощью прокси-сервера UIAppearance.

Пока класс UILabel соответствует протоколу UIAppearanceContainer, проверка UILabel.h показывает, что ни один из его свойств не помечен UI_APPEARANCE_SELECTOR, предпосылка для использования UIAppearance.

Bugger.

Ответ 2

Я подклассифицировал UILabel

@interface SmallLabel : UILabel

@end

@implementation SmallLabel

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

@end

Затем я использую outerWhenContainedIn:

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

Это работает, чтобы использовать желаемый шрифт для всех SmallLabels в моем приложении. Мне просто нужно установить пользовательский класс в SmallLabel в XCode Identity Inspector. Кажется, что он не работает с ярлыками, создаваемыми программно, только в NIB.

После дальнейшего тестирования этот метод не всегда работает надежно.

Ответ 3

Следующий код работал у меня с помощью 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`

Ответ 4

В Swift вы выполняете следующее, чтобы настроить атрибуты внешнего вида для UILabel, когда они содержатся в UITableViewHeaderFooterView:

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 18)
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).textColor = .white

Это применимо к атрибуту textLabel, когда вы используете UITableViewHeaderFooterView в:

 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, так как эти представления заголовков разделов кажутся переопределенными по умолчанию, даже если вы настраиваете UITableViewHeaderFooterView.textLabel в viewForHeaderInSection