gpt4 book ai didi

ios - 是否可以为 UILabel 中的一个字符设置不同的颜色?

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:00 24 4
gpt4 key购买 nike

我一直在使用 Xcode 开发一个小项目。它使用了很多标签、文本字段等。我已经完成了大部分布局、约束以及表单、标题等。之后,客户宣布对于所有必填字段,应该有一个红色星号在标签旁边。

说我懒惰吧,但我宁愿不返回到我的所有表单,添加大量带有星号的标签,然后重新进行自动布局以适应新标签。

那么,有没有一种方法可以更改 UILabel 中特定字符(在本例中为星号)的颜色,而其余文本保持黑色?

最佳答案

您可以使用 NSMutableAttributedString。您可以使用不同的颜色、字体、大小、...设置字符串的特定范围。

例如:

 var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2

attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
// here you change the character to red color
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
label.attributedText = attributedString

引用:Use multiple font colors in a single label - Swift

你可以改变很多字符串的属性。来自苹果的引用:https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html

关于ios - 是否可以为 UILabel 中的一个字符设置不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34808297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com