我在使用 Storyboard创建的 ViewController 中有一个 UILabel。标签文本的字体、大小和颜色及其对齐方式——全部在 Storyboard 中设置。 Storyboard中的标签连接到我名为 p_patientNameLbl 的文件中的导出。
现在我正尝试以编程方式更改标签的文本,如下所示:
[self.p_patientNameLbl setText:@"Vasya"];
我看不到新文本,直到我意识到 Storyboard中的原始标签是黑底白字,但显然在我如上所述更改标签文本后,所有字体属性都已重置,现在是黑色背景上的黑色文字,因此看不到。一旦我以编程方式设置颜色:
[self.p_patientNameLbl setTextColor:[UIColor whiteColor]];
我可以看到新标签,但所有其他字体属性和对齐方式仍然是错误的。
有没有一种方法可以仅更改标签的文本,而无需以编程方式设置所有其余属性?我想一定有办法,因为我不想在代码中格式化我的界面!
最佳答案
这对我有用:
- (void)setText:(NSString *)text withExistingAttributesInLabel:(UILabel *)label {
// Check label has existing text
if ([label.attributedText length]) {
// Extract attributes
NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL];
// Set new text with extracted attributes
label.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
}
...
[self setText:@"Some text" withExistingAttributesInLabel:self.aLabel];
关于ios - 更改 UILabel 文本但保留其余属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14488069/