是否可以为UILabel中的一个角色设置不同的颜色?

zac*_*con 3 xcode uilabel ios swift swift2

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

叫我懒惰,但我宁愿不回到我的所有表格,添加许多带星号的标签,然后重新进行自动布局以容纳新标签.

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

tul*_*dev 10

你可以用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
Run Code Online (Sandbox Code Playgroud)

参考:在单个标签中使用多种字体颜色 - Swift

您可以更改String的许多属性.来自苹果的参考:https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html


Ram*_*h_T 5

let text = "Sample text *"
let range = (text as NSString).rangeOfString("*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

    //Apply to the label
    myLabel.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)

  • 取自对[此问题](http://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift)的回答。 (2认同)

归档时间:

查看次数:

10583 次

最近记录:

8 年,7 月 前