你如何使用 NSAttributedString?

Posted

技术标签:

【中文标题】你如何使用 NSAttributedString?【英文标题】:How do you use NSAttributedString? 【发布时间】:2011-03-29 18:46:12 【问题描述】:

NSStringNSMutableStrings 中不可能有多种颜色。所以我听说了一些关于 NSAttributedString 的消息,它是随 iPad SDK 3.2(或大约 3.2)引入的,并且从 iPhone SDK 4.0 beta开始在 iPhone 上可用>.

我想要一个具有三种颜色的字符串。

我不使用 3 个单独的 NSStrings 的原因是因为三个 NSAttributedString 子字符串中的每一个的长度经常变化,所以我宁愿不使用任何计算来重新定位 3 个单独的 NSString 对象.

如果可以使用NSAttributedString,我该怎么做 - (如果不能使用 NSAttributed 字符串,你会怎么做):

编辑: 请记住,@"first"@"second"@"third" 随时会被其他字符串替换。所以使用硬编码的 NSRange 值是行不通的。

【问题讨论】:

Attributed strings in Swift NSAttributeString 的 Swift 代码:***.com/questions/27728466/… 【参考方案1】:

在构建属性字符串时,我更喜欢使用可变子类,只是为了保持简洁。

话虽如此,下面是创建三色属性字符串的方法:

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

在浏览器中输入。 警告实现者

显然,您不会在这样的范围内进行硬编码。也许您可以这样做:

NSDictionary *wordToColorMapping = ....;  //an NSDictionary of NSString => UIColor pairs
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@""];
for (NSString *word in wordToColorMapping) 
  UIColor *color = [wordToColorMapping objectForKey:word];
  NSDictionary *attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
  NSAttributedString *subString = [[NSAttributedString alloc] initWithString:word attributes:attributes];
  [string appendAttributedString:subString];
  [subString release];


//display string

【讨论】:

您能告诉我如何将属性字符串分配给标签吗? @SyedFarazHaiderZaidi UIKit 没有内置任何东西可以接受NSAttributedString。不过也有开源的东西,比如OHAttributedLabel。 如果您在 ios 上使用 CoreText.framework,您可能需要常量 kCTForegroundColorAttributeName 而不是 NSForegroundColorAttributeName 在刚刚发布的 iOS6 中(这样我就可以不用保密协议了),你可以做类似 myLabel.attributedText = attributesString;时间到了……我已经等了好几年了。 警告:字典键是无序的。不要使用上面的代码,你会失去对字符串显示顺序的控制。【参考方案2】:

这个问题已经回答了......但我想展示如何添加阴影并使用 NSAttributedString 更改字体,这样当人们搜索这个主题时,他们就不必继续寻找了。

#define FONT_SIZE 20
#define FONT_HELVETICA @"Helvetica-Light"
#define BLACK_SHADOW [UIColor colorWithRed:40.0f/255.0f green:40.0f/255.0f blue:40.0f/255.0f alpha:0.4f]

NSString*myNSString = @"This is my string.\nIt goes to a second line.";                

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
               paragraphStyle.alignment = NSTextAlignmentCenter;
             paragraphStyle.lineSpacing = FONT_SIZE/2;
                     UIFont * labelFont = [UIFont fontWithName:FONT_HELVETICA size:FONT_SIZE];
                   UIColor * labelColor = [UIColor colorWithWhite:1 alpha:1];
                       NSShadow *shadow = [[NSShadow alloc] init];
                 [shadow setShadowColor : BLACK_SHADOW];
                [shadow setShadowOffset : CGSizeMake (1.0, 1.0)];
            [shadow setShadowBlurRadius : 1];

NSAttributedString *labelText = [[NSAttributedString alloc] initWithString : myNSString
                      attributes : @
   NSParagraphStyleAttributeName : paragraphStyle,
             NSKernAttributeName : @2.0,
             NSFontAttributeName : labelFont,
  NSForegroundColorAttributeName : labelColor,
           NSShadowAttributeName : shadow ];

这是一个 Swift 版本...

警告! 这适用于4s。

对于 5 秒,您必须将所有 Float 值更改为 Double 值(因为编译器尚未正常工作)

用于字体选择的 Swift 枚举:

enum FontValue: Int 
    case FVBold = 1 , FVCondensedBlack, FVMedium, FVHelveticaNeue, FVLight, FVCondensedBold, FVLightItalic, FVUltraLightItalic, FVUltraLight, FVBoldItalic, FVItalic

用于枚举访问的 Swift 数组(需要,因为枚举不能使用 '-'):

func helveticaFont (index:Int) -> (String) 
    let fontArray = [
    "HelveticaNeue-Bold",
    "HelveticaNeue-CondensedBlack",
    "HelveticaNeue-Medium",
    "HelveticaNeue",
    "HelveticaNeue-Light",
    "HelveticaNeue-CondensedBold",
    "HelveticaNeue-LightItalic",
    "HelveticaNeue-UltraLightItalic",
    "HelveticaNeue-UltraLight",
    "HelveticaNeue-BoldItalic",
    "HelveticaNeue-Italic",
    ]
    return fontArray[index]

Swift 属性文本函数:

func myAttributedText (myString:String, mySize: Float, myFont:FontValue) -> (NSMutableAttributedString) 

    let shadow = NSShadow()
    shadow.shadowColor = UIColor.textShadowColor()
    shadow.shadowOffset = CGSizeMake (1.0, 1.0)
    shadow.shadowBlurRadius = 1

    let paragraphStyle = NSMutableParagraphStyle.alloc()
    paragraphStyle.lineHeightMultiple = 1
    paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
    paragraphStyle.alignment = NSTextAlignment.Center

    let labelFont = UIFont(name: helveticaFont(myFont.toRaw()), size: mySize)
    let labelColor = UIColor.whiteColor()

    let myAttributes :Dictionary = [NSParagraphStyleAttributeName : paragraphStyle,
                                              NSKernAttributeName : 3, // (-1,5)
                                              NSFontAttributeName : labelFont,
                                   NSForegroundColorAttributeName : labelColor,
                                            NSShadowAttributeName : shadow]

    let myAttributedString = NSMutableAttributedString (string: myString, attributes:myAttributes)

    // add new color 
    let secondColor = UIColor.blackColor()
    let stringArray = myString.componentsSeparatedByString(" ")
    let firstString: String? = stringArray.first
    let letterCount = countElements(firstString!)
    if firstString 
        myAttributedString.addAttributes([NSForegroundColorAttributeName:secondColor], range:NSMakeRange(0,letterCount))
    

    return  myAttributedString

用于在字符串数组中查找范围的第一个和最后一个扩展:

extension Array 
    var last: T? 
        if self.isEmpty 
            NSLog("array crash error - please fix")
            return self [0]
         else 
            return self[self.endIndex - 1]
        
    


extension Array 
    var first: T? 
        if self.isEmpty 
            NSLog("array crash error - please fix")
            return self [0]
         else 
            return self [0]
        
    

新颜色:

extension UIColor 
    class func shadowColor() -> UIColor 
        return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.3)
    
    class func textShadowColor() -> UIColor 
        return UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 0.5)
    
    class func pastelBlueColor() -> UIColor 
        return UIColor(red: 176.0/255.0, green: 186.0/255.0, blue: 255.0/255.0, alpha: 1)
    
    class func pastelYellowColor() -> UIColor 
        return UIColor(red: 255.0/255.0, green: 238.0/255.0, blue: 140.0/255.0, alpha: 1)
    

我的宏替换:

enum MyConstants: Float 
    case CornerRadius = 5.0

带有属性文本的按钮制作器:

func myButtonMaker (myView:UIView) -> UIButton 

    let myButton = UIButton.buttonWithType(.System) as UIButton
    myButton.backgroundColor = UIColor.pastelBlueColor()
    myButton.showsTouchWhenHighlighted = true;
    let myCGSize:CGSize = CGSizeMake(100.0, 50.0)
    let myFrame = CGRectMake(myView.frame.midX - myCGSize.height,myView.frame.midY - 2 * myCGSize.height,myCGSize.width,myCGSize.height)
    myButton.frame = myFrame
    let myTitle = myAttributedText("Button",20.0,FontValue.FVLight)
    myButton.setAttributedTitle(myTitle, forState:.Normal)

    myButton.layer.cornerRadius = myButton.bounds.size.width / MyConstants.CornerRadius.toRaw()
    myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    myButton.tag = 100
    myButton.bringSubviewToFront(myView)
    myButton.layerGradient()

    myView.addSubview(myButton)

    return  myButton

我的带有属性文本、阴影和圆角的 UIView/UILabel 制造商:

func myLabelMaker (myView:UIView) -> UIView 

    let myFrame = CGRectMake(myView.frame.midX / 2 , myView.frame.midY / 2, myView.frame.width/2, myView.frame.height/2)
    let mylabelFrame = CGRectMake(0, 0, myView.frame.width/2, myView.frame.height/2)

    let myBaseView = UIView()
    myBaseView.frame = myFrame
    myBaseView.backgroundColor = UIColor.clearColor()

    let myLabel = UILabel()
    myLabel.backgroundColor=UIColor.pastelYellowColor()
    myLabel.frame = mylabelFrame

    myLabel.attributedText = myAttributedText("This is my String",20.0,FontValue.FVLight)
    myLabel.numberOfLines = 5
    myLabel.tag = 100
    myLabel.layer.cornerRadius = myLabel.bounds.size.width / MyConstants.CornerRadius.toRaw()
    myLabel.clipsToBounds = true
    myLabel.layerborders()

    myBaseView.addSubview(myLabel)

    myBaseView.layerShadow()
    myBaseView.layerGradient()

    myView.addSubview(myBaseView)

    return myLabel

通用阴影添加:

func viewshadow<T where T: UIView> (shadowObject: T)

    let layer = shadowObject.layer
    let radius = shadowObject.frame.size.width / MyConstants.CornerRadius.toRaw();
    layer.borderColor = UIColor.whiteColor().CGColor
    layer.borderWidth = 0.8
    layer.cornerRadius = radius
    layer.shadowOpacity = 1
    layer.shadowRadius = 3
    layer.shadowOffset = CGSizeMake(2.0,2.0)
    layer.shadowColor = UIColor.shadowColor().CGColor

视图样式的视图扩展:

extension UIView 
    func layerborders() 
        let layer = self.layer
        let frame = self.frame
        let myColor = self.backgroundColor
        layer.borderColor = myColor.CGColor
        layer.borderWidth = 10.8
        layer.cornerRadius = layer.borderWidth / MyConstants.CornerRadius.toRaw()
    

    func layerShadow() 
        let layer = self.layer
        let frame = self.frame
        layer.cornerRadius = layer.borderWidth / MyConstants.CornerRadius.toRaw()
        layer.shadowOpacity = 1
        layer.shadowRadius = 3
        layer.shadowOffset = CGSizeMake(2.0,2.0)
        layer.shadowColor = UIColor.shadowColor().CGColor
    

    func layerGradient() 
        let layer = CAGradientLayer()
        let size = self.frame.size
        layer.frame.size = size
        layer.frame.origin = CGPointMake(0.0,0.0)
        layer.cornerRadius = layer.bounds.size.width / MyConstants.CornerRadius.toRaw();

        var color0 = CGColorCreateGenericRGB(250.0/255, 250.0/255, 250.0/255, 0.5)
        var color1 = CGColorCreateGenericRGB(200.0/255, 200.0/255, 200.0/255, 0.1)
        var color2 = CGColorCreateGenericRGB(150.0/255, 150.0/255, 150.0/255, 0.1)
        var color3 = CGColorCreateGenericRGB(100.0/255, 100.0/255, 100.0/255, 0.1)
        var color4 = CGColorCreateGenericRGB(50.0/255, 50.0/255, 50.0/255, 0.1)
        var color5 = CGColorCreateGenericRGB(0.0/255, 0.0/255, 0.0/255, 0.1)
        var color6 = CGColorCreateGenericRGB(150.0/255, 150.0/255, 150.0/255, 0.1)

        layer.colors = [color0,color1,color2,color3,color4,color5,color6]
        self.layer.insertSublayer(layer, atIndex: 2)
    

实际视图确实加载了函数:

func buttonPress (sender:UIButton!) 
    NSLog("%@", "ButtonPressed")


override func viewDidLoad() 
    super.viewDidLoad()

    let myLabel = myLabelMaker(myView)
    let myButton = myButtonMaker(myView)

    myButton.addTarget(self, action: "buttonPress:", forControlEvents:UIControlEvents.TouchUpInside)

    viewshadow(myButton)
    viewshadow(myLabel)


【讨论】:

【参考方案3】:

我认为,使用regular expressions 查找应用属性的范围是一种非常方便的方法。我就是这样做的:

NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];

NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) 
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];


NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) 
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];


[self.textView setAttributedText:goodText];

我正在搜索可用属性的列表,但在此处和类参考的第一页中没有找到它们。所以我决定在这里发布相关信息。

Standard Attributes

属性字符串支持文本的以下标准属性。如果键不在字典中,则使用下面描述的默认值。

NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
NSString *NSForegroundColorAttributeName;
NSString *NSUnderlineStyleAttributeName;
NSString *NSSuperscriptAttributeName;
NSString *NSBackgroundColorAttributeName;
NSString *NSAttachmentAttributeName;
NSString *NSLigatureAttributeName;
NSString *NSBaselineOffsetAttributeName;
NSString *NSKernAttributeName;
NSString *NSLinkAttributeName;
NSString *NSStrokeWidthAttributeName;
NSString *NSStrokeColorAttributeName;
NSString *NSUnderlineColorAttributeName;
NSString *NSStrikethroughStyleAttributeName;
NSString *NSStrikethroughColorAttributeName;
NSString *NSShadowAttributeName;
NSString *NSObliquenessAttributeName;
NSString *NSExpansionAttributeName;
NSString *NSCursorAttributeName;
NSString *NSToolTipAttributeName;
NSString *NSMarkedClauseSegmentAttributeName;
NSString *NSWritingDirectionAttributeName;
NSString *NSVerticalGlyphFormAttributeName;
NSString *NSTextAlternativesAttributeName;

NSAttributedString programming guide

完整的课程参考是here。

【讨论】:

感谢列出属性键(否则很难找到) 你会如何在 Swift 中做到这一点?【参考方案4】:

我写了助手来轻松添加属性:

- (void)addColor:(UIColor *)color substring:(NSString *)substring;
- (void)addBackgroundColor:(UIColor *)color substring:(NSString *)substring;
- (void)addUnderlineForSubstring:(NSString *)substring;
- (void)addStrikeThrough:(int)thickness substring:(NSString *)substring;
- (void)addShadowColor:(UIColor *)color width:(int)width height:(int)height radius:(int)radius substring:(NSString *)substring;
- (void)addFontWithName:(NSString *)fontName size:(int)fontSize substring:(NSString *)substring;
- (void)addAlignment:(NSTextAlignment)alignment substring:(NSString *)substring;
- (void)addColorToRussianText:(UIColor *)color;
- (void)addStrokeColor:(UIColor *)color thickness:(int)thickness substring:(NSString *)substring;
- (void)addVerticalGlyph:(BOOL)glyph substring:(NSString *)substring;

https://github.com/shmidt/MASAttributes

您也可以通过 CocoaPods 安装:pod 'MASAttributes', '~&gt; 1.0.0'

【讨论】:

【参考方案5】:

我总是发现使用属性字符串是一个非常冗长和乏味的过程。

所以我制作了一个 Mac 应用程序,它可以为您创建所有代码。

https://itunes.apple.com/us/app/attributed-string-creator/id730928349?mt=12

【讨论】:

这里还有一个类别/博客文章,用于使 NSAttributed 字符串更容易一些。 raizlabs.com/dev/2014/03/nsattributedstring-creation-helpers【参考方案6】:

从 iOS 7 开始,您可以使用带有 html 语法的 NSAttributedString

NSURL *htmlString = [[NSBundle mainBundle]  URLForResource: @"string"     withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
                                                                                       options:@NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType
                                                                            documentAttributes:nil
                                                                                         error:nil];
textView.attributedText = stringWithHTMLAttributes;// you can use a label also

你必须将文件“string.html”添加到你的项目中,html的内容可以是这样的:

<html>
  <head>
    <style type="text/css">
      body 
        font-size: 15px;
        font-family: Avenir, Arial, sans-serif;
      
      .red 
        color: red;
      
      .green 
        color: green;
      
      .blue 
        color: blue;
      
    </style>
  </head>
  <body>
    <span class="red">first</span><span class="green">second</span><span class="blue">third</span>
  </body>
</html>  

现在,您可以随意使用NSAttributedString,即使没有 HTML 文件,例如:

//At the top of your .m file
#define RED_OCCURENCE -red_occurence-
#define GREEN_OCCURENCE -green_occurence-
#define BLUE_OCCURENCE -blue_occurence-
#define HTML_TEMPLATE @"<span style=\"color:red\">-red_occurence-</span><span style=\"color:green\">-green_occurence-</span><span style=\"color:blue\">-blue_occurence-</span></body></html>"

//Where you need to use your attributed string
NSString *string = [HTML_TEMPLATE stringByReplacingOccurrencesOfString:RED_OCCURENCE withString:@"first"] ;
string = [string stringByReplacingOccurrencesOfString:GREEN_OCCURENCE   withString:@"second"];
string = [string stringByReplacingOccurrencesOfString:BLUE_OCCURENCE    withString:@"third"];

NSData* cData = [string dataUsingEncoding:NSUTF8StringEncoding];

NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:cData
                                                                                options:@NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType
                                                                        documentAttributes:nil
                                                                                     error:nil];
textView.attributedText = stringWithHTMLAttributes;

Source

【讨论】:

【参考方案7】:

您可以在Swift 中加载HTML 属性字符串,如下所示

   var Str = NSAttributedString(
   data: htmlstring.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
   options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
   documentAttributes: nil,
   error: nil)

   label.attributedText = Str  

从文件加载html

   if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) 

   let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
        textView.attributedText = attributedString
        textView.editable = false
    

http://sketchytech.blogspot.in/2013/11/creating-nsattributedstring-from-html.html

并根据您所需的属性设置字符串..按照这个..http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/

【讨论】:

【参考方案8】:
- (void)changeColorWithString:(UILabel *)uilabel stringToReplace:(NSString *) stringToReplace uiColor:(UIColor *) uiColor
    NSMutableAttributedString *text =
    [[NSMutableAttributedString alloc]
     initWithAttributedString: uilabel.attributedText];

    [text addAttribute: NSForegroundColorAttributeName value:uiColor range:[uilabel.text rangeOfString:stringToReplace]];

    [uilabel setAttributedText: text];


【讨论】:

【参考方案9】:

此解决方案适用于任何长度

NSString *strFirst = @"Anylengthtext";
NSString *strSecond = @"Anylengthtext";
NSString *strThird = @"Anylengthtext";

NSString *strComplete = [NSString stringWithFormat:@"%@ %@ %@",strFirst,strSecond,strThird];

NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor redColor]
              range:[strComplete rangeOfString:strFirst]];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor yellowColor]
              range:[strComplete rangeOfString:strSecond]];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor blueColor]
              range:[strComplete rangeOfString:strThird]];


self.lblName.attributedText = attributedString;

【讨论】:

请注意,对于 SWIFT,您仍需要使用 NSString,因为范围的原因,请查看此答案:***.com/a/27041376/1736679【参考方案10】:

我创建了一个库,使这变得更容易。查看ZenCopy.

您可以创建样式对象,和/或将它们设置为键以供以后参考。像这样:

ZenCopy.manager.config.setStyles 
    return [
        "token": Style(
            color: .blueColor(), // optional
            // fontName: "Helvetica", // optional
            fontSize: 14 // optional
        )
    ]

然后,您可以轻松地构造字符串并设置它们的样式并设置参数:)

label.attributedText = attributedString(
                                ["$0 ".style("token") "is dancing with ", "$1".style("token")], 
                          args: ["JP", "Brock"]
)

您还可以使用正则表达式搜索轻松地设置样式!

let atUserRegex = "(@[A-Za-z0-9_]*)"
mutableAttributedString.regexFind(atUserRegex, addStyle: "token")

这会将前面带有“@”的所有单词设置为“token”样式。 (例如@jpmcglone)

我仍然需要使用 NSAttributedString 提供的所有功能使其正常工作,但我认为 fontNamefontSize 和颜色覆盖了大部分内容。期待很快会有很多更新:)

如果您需要,我可以帮助您开始。也在寻找反馈,所以如果它能让你的生活更轻松,我会说任务完成了。

【讨论】:

【参考方案11】:

为了解决这类问题,我在 swift 中创建了名为 Atributika 的库。

let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
        Style("r").foregroundColor(.red),
        Style("g").foregroundColor(.green),
        Style("b").foregroundColor(.blue)).attributedString

label.attributedText = str

你可以在这里找到它https://github.com/psharanda/Atributika

【讨论】:

【参考方案12】:

带有属性字符串扩展的更简单的解决方案。

extension NSMutableAttributedString 

    // this function attaches color to string    
    func setColorForText(textToFind: String, withColor color: UIColor) 
        let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    


试试这个看看(在 Swift 3 和 4 中测试)

let label = UILabel()
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
let first = "first"
let second = "second"
let third = "third"
let stringValue = "\(first)\(second)\(third)"  // or direct assign single string value like "firstsecondthird"

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: first, withColor: UIColor.red)   // use variable for string "first"
attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second"
attributedString.setColorForText(textToFind: third, withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

这是预期的结果:

【讨论】:

【参考方案13】:

在 Swift 4 中:

let string:NSMutableAttributedString = 

    let mutableString = NSMutableAttributedString(string: "firstsecondthird")

    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: NSRange(location: 0, length: 5))
    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green , range: NSRange(location: 5, length: 6))
    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 11, length: 5))
    return mutableString
()

print(string)

【讨论】:

请不要对多个问题发布相同的答案。发布一个好的答案,然后投票/标记以关闭其他问题作为重复问题。如果问题不是重复的,调整您对该问题的回答。 我正在尝试用 Swift 给出答案。我接受了它的副本。不期待投票 道歉。我已经删除了答案【参考方案14】:

斯威夫特 4

let combination = NSMutableAttributedString()

var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()

let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]

let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]

let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
                                 NSAttributedStringKey.foregroundColor: UIColor.red]

if let regular = attrRegular as? [NSAttributedStringKey : NSObject]
    part1 = NSMutableAttributedString(string: "first", attributes: regular)


if let bold = attrRegular as? [NSAttributedStringKey : NSObject]
    part2 = NSMutableAttributedString(string: "second", attributes: bold)


if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]
    part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)


combination.append(part1)
combination.append(part2)
combination.append(part3)

属性列表请看这里 NSAttributedStringKey on Apple Docs

【讨论】:

【参考方案15】:

超级简单的方法。

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

更多详情请点击这里; https://github.com/iOSTechHub/AttributedString

【讨论】:

以上是关于你如何使用 NSAttributedString?的主要内容,如果未能解决你的问题,请参考以下文章

你如何抚摸 NSAttributedString 的 _outside_ ?

如何将 HTML 的 CSS 添加到 NSAttributedString?

NSAttributedString:将图像适合容器

NSAttributedString 上的可访问性(旁白)

NSAttributedString

如何在 SwiftUI 中使用 NSAttributedString 和 ScrollView?