【问题标题】:How to retrieve titleLabel on UIButton's prepareForInterfaceBuilder?如何在 UIButton 的 prepareForInterfaceBuilder 上检索 titleLabel?
【发布时间】:2016-01-23 16:03:22
【问题描述】:

我继承了UIButton 并具有以下prepareForInterfaceBuilder 函数:

- (void)prepareForInterfaceBuilder {
    NSString *string = [self titleForState:UIControlStateNormal];
    NSAttributedString *attrString = [[NSAttributedString alloc]
                                      initWithString:string
                                      attributes:@{
                                                   NSKernAttributeName : @4,
                                                   NSForegroundColorAttributeName : [UIColor whiteColor]
                                                   }];
    [self setAttributedTitle:attrString forState:UIControlStateNormal];
}

在 Interface Builder 中查看时崩溃,因为字符串变量返回 nil,即使我在 Interface Builder 中将“测试”设置为标题。我也尝试通过调用self.titleLabel.text 来检索文本,但这也会导致nil

如何在此函数中正确检索 titleLabel 的文本? 目前使用 Xcode 7.1 (7B91b)。

【问题讨论】:

  • 能否分享一下崩溃日志?
  • 我试着玩prepareForInterfaceBuilder,看起来它不允许对按钮标题做任何事情。但是设置标题颜色\其他东西工作正常
  • @jamil65able:如何从界面生成器获取崩溃日志?请记住,这不是在标准运行时完成的。查看我的故事板时,我在问题导航器中收到代理崩溃消息。
  • @VitaliyGozhenko:奇怪的是,您可以从UILabel 检索文本,但不能从UIButton 检索文本
  • 可能是因为titleLabel在运行时初始化,而不是在IB中

标签: ios xcode uibutton interface-builder


【解决方案1】:

您可以直接将 Attibuted 字符串设置为 UIButton 的 Lable

NSString *string = @"Your text here";
NSAttributedString *attrString = [[NSAttributedString alloc]
                                  initWithString:string
                                  attributes:@{
                                               NSKernAttributeName : @4,
                                               NSForegroundColorAttributeName : [UIColor whiteColor]
                                               }];
[yourCustomButton setAttributedTitle:attrString forState:UIControlStateNormal];

【讨论】:

  • 我想将我在 IB 中设置的文本转换为带格式的属性字符串。我想调整这个子类 UIButton 的 50 个实例以应用字距调整。如您在第一行代码中提到的那样手动设置字符串是不可行的..
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多