覆盖 UIButton setAttributedTitle:forState:

Overriding UIButton setAttributedTitle:forState:

我正在尝试覆盖 UIButton setAttributedTitle:forState: 以便在使用子类的任何地方设置一些默认字距调整。此代码创建正确的 NSAttributedString 并适用于我使用 Interface Builder 创建的任何 UIButtons:

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state
{
    NSMutableAttributedString* attributeText = [[[NSAttributedString alloc] initWithAttributedString:title] mutableCopy];
    [attributeText addAttributes:@{NSKernAttributeName: @(kDefaultKerning)} range:[attributeText fullRange]];
    self.titleLabel.attributedText = attributeText;
    [self setNeedsDisplay];
}

但它不适用于我在代码中创建的任何 UIButton 子类:

[_myButton setAttributedTitle:attributedString forState:UIControlStateNormal];

所以我尝试调用 super 而不是 self.titleLabel.attributedText = attributeText;:

[super setAttributedTitle:title forState:state];

它适用于在代码中创建的按钮,但现在不适用于 Interface Builder 按钮。

据我所知,Interface Builder 只是调用 setAttributedText,这是怎么回事?我怎样才能让这个覆盖同时适用于代码生成的按钮和 Interface Builder?

傻我。当然 [super setAttributedTitle:title forState:state]; 不起作用,因为我将其设置为 title 而不是 attributedText.

解决方案:

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state
{
    NSMutableAttributedString* attributeText = [[[NSAttributedString alloc] initWithAttributedString:title] mutableCopy];
    [attributeText addAttributes:@{NSKernAttributeName: @(kDefaultKerning)} range:[attributeText fullRange]];
    [super setAttributedTitle:attributeText forState:state];
    [self setNeedsDisplay];
}