【问题标题】:Change the text of an attributed UILabel without losing the formatting?在不丢失格式的情况下更改属性 UILabel 的文本?
【发布时间】:2012-10-03 10:03:58
【问题描述】:

在故事板中,我布置了一组带有各种格式选项的标签。

然后我做:

label.text = @"Set programmatically";

所有格式都丢失了!这在 iOS5 中运行良好。

一定有办法只更新文本字符串而不重新编码所有格式?!

label.attributedText.string 

只读。

提前致谢。

【问题讨论】:

    标签: iphone ios xcode ios6


    【解决方案1】:

    您可以将属性提取为字典:

    NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL];
    

    然后将它们与新文本一起添加回来:

    label.attributedText = [[NSAttributedString alloc] initWithString:@"Some text" attributes:attributes];
    

    这假设标签中有文本,否则你会崩溃,所以你应该先检查一下:

    if ([self.label.attributedText length]) {...}
    

    【讨论】:

    • 其实iOS应该是默认的,反正我们有办法。谢谢,你的建议对我有帮助。
    【解决方案2】:

    AttributeString 包含它的所有格式数据。标签对格式一无所知。

    您可以将属性存储为单独的字典,然后当您更改属性字符串时,您可以使用:

    [[NSAttributedString alloc] initWithString:@"" attributes:attributes range:range];
    

    唯一的其他选择是再次构建属性备份。

    【讨论】:

      【解决方案3】:

      虽然是 iOS 编程新手,但我很快就遇到了同样的问题。在 iOS 中,我的经验是

      1. Lewis42 的问题一直出现
      2. josef 关于提取和重新应用属性的建议确实 不起作用:返回空属性字典。

      环顾四周,我遇到了This Post 并遵循了该建议,我最终使用了这个:

      - (NSMutableAttributedString *)SetLabelAttributes:(NSString *)input col:(UIColor *)col size:(Size)size {
      
      NSMutableAttributedString *labelAttributes = [[NSMutableAttributedString alloc] initWithString:input];
      
      UIFont *font=[UIFont fontWithName:@"Helvetica Neue" size:size];
      
      NSMutableParagraphStyle* style = [NSMutableParagraphStyle new];
      style.alignment = NSTextAlignmentCenter;
      
      [labelAttributes addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, labelAttributes.length)];
      [labelAttributes addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, labelAttributes.length)];
      [labelAttributes addAttribute:NSForegroundColorAttributeName value:col range:NSMakeRange(0, labelAttributes.length)];
      
      return labelAttributes;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 2014-12-06
        • 1970-01-01
        相关资源
        最近更新 更多