ios 更改 UILabel 文本但保留其余属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14488069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:58:42  来源:igfitidea点击:

Changing UILabel text but keeping the rest of the attributes

iosobjective-cuilabel

提问by PeterD

I have a UILabel in my ViewController created using storyboards. The font, size and color of the label's text, its alignment - all set in the storyboard. The label in the storyboard is connected to the outlet in my file called p_patientNameLbl.

我的 ViewController 中有一个 UILabel 使用故事板创建。标签文本的字体、大小和颜色、对齐方式 - 都在故事板中设置。故事板中的标签连接到我的文件中名为p_patientNameLbl的插座。

Now I am trying to change the text of the label programatically, like this:

现在我试图以编程方式更改标签的文本,如下所示:

[self.p_patientNameLbl setText:@"Vasya"];

I could not see the new text, until I realized that the original label in the storyboard was white on black background, but apparently after I changed the label's text as above, all the font attributes have been reset and now it was a black text on black background, and therefore not seen. Once I set the color programmatically:

我看不到新文本,直到我意识到故事板中的原始标签是黑色背景上的白色,但显然在我如上所述更改标签的文本后,所有字体属性都已重置,现在它是黑​​色文本黑色背景,因此看不见。一旦我以编程方式设置颜色:

[self.p_patientNameLbl setTextColor:[UIColor whiteColor]];

I could see the new label, but all the rest of the font attributes and alignment were still wrong.

我可以看到新标签,但所有其余的字体属性和对齐方式仍然错误。

Is there a way to change onlythe text of the label without having then programmatically to set all the rest of the attributes? I would imagine there must be a way, since I don't want to be formatting my interface in the code!

有没有办法更改标签的文本,而无需以编程方式设置所有其余属性?我想一定有办法,因为我不想在代码中格式化我的界面!

采纳答案by Mick MacCallum

This is happening because you're telling Interface builder to take a label that had pre-defined attributes set on its text and replace this attributed text with plain text. Instead of setText, or setTextColoryou have to use setAttributedTextand specify the attributes that you wish to pass to the attributed string.

发生这种情况是因为您告诉界面构建器采用在其文本上设置了预定义属性的标签,并用纯文本替换此属性文本。而不是setText, 或者setTextColor您必须使用setAttributedText并指定您希望传递给属性字符串的属性。

Here's an example of how to apply an attributed string to your label programmatically. I'm not aware of any better way, but using this, you can make changes to the text or text color and as long as you set your other attributes along with them, all changes will be applied correctly.

下面是如何以编程方式将属性字符串应用于标签的示例。我不知道有什么更好的方法,但是使用它,您可以更改文本或文本颜色,只要您设置其他属性,所有更改都将正确应用。

[myLabel setAttributedText:[self myLabelAttributes:@"Some awesome text!"]];

....................

- (NSMutableAttributedString *)myLabelAttributes:(NSString *)input
{
    NSMutableAttributedString *labelAttributes = [[NSMutableAttributedString alloc] initWithString:input];

    [labelAttributes addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-5.0] range:NSMakeRange(0, labelAttributes.length)];
    [labelAttributes addAttribute:NSStrokeColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, labelAttributes.length)];
    [labelAttributes addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, labelAttributes.length)];

    return labelAttributes;
}

回答by josef

This works for me:

这对我有用:

- (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];

回答by Bart?omiej Semańczyk

One line implementation in Swift:

Swift 中的一行实现:

label.attributedText = NSAttributedString(string: "text", attributes: label.attributedText!.attributesAtIndex(0, effectiveRange: nil))

回答by Oz Shabat

Swift 4

斯威夫特 4

label.attributedText = NSAttributedString(string: "new label text", attributes: label.attributedText!.attributes(at: 0, effectiveRange: nil))

(a few minors changes from Bart?omiej Semańczyk answer)

(Bart?omiej Semańczyk 的回答中有一些未成年人的变化)

回答by Kostas Williams

0x7fffffff, thanks for your tip, that worked for me. In iOS6 some other advices here did not work eg. extracting the attributes and reapplying them.

0x7fffffff,感谢您的提示,这对我有用。在 iOS6 中,这里的一些其他建议不起作用,例如。提取属性并重新应用它们。

In my case I was losing quite a few useful attributes, including the font, so here's my solution:

就我而言,我丢失了很多有用的属性,包括字体,所以这是我的解决方案:

- (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;
}

then apply it to the UILabel like this:

然后像这样将它应用到 UILabel 上:

[self.myLabel setAttributedText:[self CurrentSetLabelAttributes:[NSString stringWithFormat:@"%d", myClass.text] col:[UIColor redColor]  size:50.0f]];

回答by Qiulang

Instead of storing the old attributes and creating a new NSAttributedString with the changed text and stored attributes, a relatively easier way will be:

与存储旧属性并使用更改的文本和存储的属性创建新的 NSAttributedString 不同,一种相对更简单的方法是:

NSMutableAttributedString *attStr = [label.attributedText mutableCopy];
NSMutableString *str = attStr.mutableString;
/* change str with new text */
label.attributedText = attStr;

回答by Sam B

I have done this many times for multiple apps. I always make my labels and text in Storyboard, changing their font size, color display, alpha value etc in editor. But afterwards if I need to change the text, which I have done a multiple times, all I do is this.

我已经为多个应用程序做过很多次了。我总是在 Storyboard 中制作标签和文本,在编辑器中更改它们的字体大小、颜色显示、alpha 值等。但是之后如果我需要更改文本,我已经做了多次,我所做的就是这样。

p_patientNameLbl.textColor = [UIColor redColor];
p_patientNameLbl.text = @"My Sample Text";

thats it. all the other default properties are kept. Unless I missed something in your question?

就是这样。保留所有其他默认属性。除非我在你的问题中遗漏了什么?