更改属性UILabel的文本而不会丢失格式?

Lew*_*s42 19 iphone xcode ios ios6

在故事板中,我使用各种格式选项布局一组标签.

然后我做:

label.text = @"Set programmatically";
Run Code Online (Sandbox Code Playgroud)

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

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

label.attributedText.string 
Run Code Online (Sandbox Code Playgroud)

是只读的.

提前致谢.

jos*_*sef 29

您可以使用以下内容将属性提取为字典:

NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL];
Run Code Online (Sandbox Code Playgroud)

然后使用新文本添加它们:

label.attributedText = [[NSAttributedString alloc] initWithString:@"Some text" attributes:attributes];
Run Code Online (Sandbox Code Playgroud)

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

if ([self.label.attributedText length]) {...}
Run Code Online (Sandbox Code Playgroud)


Fog*_*ter 4

attributeString 包含其所有格式数据。唱片公司对格式一无所知。

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

[[NSAttributedString alloc] initWithString:@"" attributes:attributes range:range];
Run Code Online (Sandbox Code Playgroud)

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