【发布时间】:2012-10-03 10:03:58
【问题描述】:
在故事板中,我布置了一组带有各种格式选项的标签。
然后我做:
label.text = @"Set programmatically";
所有格式都丢失了!这在 iOS5 中运行良好。
一定有办法只更新文本字符串而不重新编码所有格式?!
label.attributedText.string
只读。
提前致谢。
【问题讨论】:
在故事板中,我布置了一组带有各种格式选项的标签。
然后我做:
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]) {...}
【讨论】:
AttributeString 包含它的所有格式数据。标签对格式一无所知。
您可以将属性存储为单独的字典,然后当您更改属性字符串时,您可以使用:
[[NSAttributedString alloc] initWithString:@"" attributes:attributes range:range];
唯一的其他选择是再次构建属性备份。
【讨论】:
虽然是 iOS 编程新手,但我很快就遇到了同样的问题。在 iOS 中,我的经验是
环顾四周,我遇到了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;
【讨论】: