【问题标题】:Overriding UIButton setAttributedTitle:forState:覆盖 UIButton setAttributedTitle:forState:
【发布时间】:2015-12-26 12:34:41
【问题描述】:

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

- (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?

【问题讨论】:

    标签: ios objective-c uibutton interface-builder nsattributedstring


    【解决方案1】:

    我傻了。当然[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];
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多