19

在情节提要中,我布置了一组带有各种格式选项的标签。

然后我做:

label.text = @"Set programmatically";

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

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

label.attributedText.string 

是只读的。

提前致谢。

4

3 回答 3

29

您可以使用以下方法将属性提取为字典:

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

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

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

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

if ([self.label.attributedText length]) {...}
于 2013-06-17T00:37:26.093 回答
4

属性字符串包含其所有格式数据。标签对格式一无所知。

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

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

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

于 2012-10-03T10:07:07.480 回答
4

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

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

环顾四周后,我遇到了这篇文章并遵循了该建议,我最终使用了这个:

- (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;
于 2013-06-20T12:58:53.017 回答