【问题标题】:How to change the color of a specific word in ios [duplicate]如何在ios中更改特定单词的颜色[重复]
【发布时间】:2013-06-20 13:34:48
【问题描述】:

我想在 IOS 5 中更改 句子 中特定单词的 颜色。 让我的字符串为NSString str = @"Your password is abc"; 我想更改密码'abc'的颜色。 请帮帮我。

提前致谢。

【问题讨论】:

标签: objective-c ios5 xcode4.2


【解决方案1】:

在 IOS 6 中,您可以通过属性文本更改特定单词的字体、textColor 和 textAlignment,您可以在此处找到相关文档

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextView_Class/Reference/UITextView.html

stackoverflow回答了同样的问题,问题的链接如下

Bold & Non-Bold Text In A Single UILabel?

【讨论】:

  • 好的..让我试试..谢谢..
【解决方案2】:

我想你正在寻找这个东西,希望它对你有用。

对于像 firstsecondthid 这样的字符串,您可以这样做。第一个用红色写,第二个用绿色写,第三个用蓝色写。

示例代码:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];  
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];  
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];  
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];  

【讨论】:

  • 我使用了这个代码。但我收到错误消息“使用未声明的标识符 NSForegroundColorAttributeName”。我该怎么办?
  • 替换这个 [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)]; with [string addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor redColor] CGColor] range:NSMakeRange(0,5)];
  • 我们如何将这个 NSMutableAttributedString 设置为标签。如果我的问题是错误的,我很抱歉。我是IOS的初学者。我使用了代码 myLabel.text = (NSString*)string;但我要崩溃了。
  • 很简单就这么办 self.attributedLabel.attributedText = string;
  • 请记住,当您处于学习阶段时,没有问题是一个愚蠢的问题。因此,您心中的任何想法都可以提出、探索并寻求答案。尝试提高你的谷歌技能。如果我的答案对您有用,请不要忘记标记为答案或投票正确。谢谢
【解决方案3】:

您可以使用RTLabel,只需在rtLBLObj.text 中设置属性文本,它将显示相关输出。只需下载并拖动RTLabel.h.m 文件到您的项目中。您可以从RTLabel 下载它

【讨论】:

  • 是的,这是一个好方法。但是如何使用这种方法将文本字段的值附加到标签上。
【解决方案4】:

正如前面的答案所提到的,您需要使用NSAttributedString 来存储格式化文本。

但是,iOS 中对 UILabels 中的属性字符串的原生支持仅在 iOS 6 中引入。

如果您想支持 iOS 5 及更低版本,周围有许多库用于显示属性字符串。我建议使用TTTAttributedLabel

【讨论】:

  • 抱歉,我对 podfile 不熟悉。有没有其他方法可以解决这个问题?
  • 您不必使用 podfile,只需将 .h.m 文件添加到您的项目中即可。
猜你喜欢
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 2021-12-01
相关资源
最近更新 更多