在情节提要中,我布置了一组带有各种格式选项的标签。
然后我做:
label.text = @"Set programmatically";
并且所有格式都丢失了!这在 iOS5 中运行良好。
一定有一种方法可以只更新文本字符串而不重新编码所有格式?!
label.attributedText.string
是只读的。
提前致谢。
您可以使用以下方法将属性提取为字典:
NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL];
然后将它们与新文本一起添加回来:
label.attributedText = [[NSAttributedString alloc] initWithString:@"Some text" attributes:attributes];
这假设标签中有文本,否则你会崩溃,所以你应该先对它进行检查:
if ([self.label.attributedText length]) {...}
属性字符串包含其所有格式数据。标签对格式一无所知。
您可以将属性存储为单独的字典,然后在更改属性字符串时可以使用:
[[NSAttributedString alloc] initWithString:@"" attributes:attributes range:range];
唯一的其他选择是再次构建属性备份。
虽然是 iOS 编程新手,但我很快就遇到了同样的问题。在 iOS 中,我的经验是
环顾四周后,我遇到了这篇文章并遵循了该建议,我最终使用了这个:
- (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;