Applying different attributes for different portions of an NSAttributedstring

北慕城南 提交于 2019-11-29 11:58:15

Make a mutable copy of the attributed string, and then use either:

-setAttributes:range:
-addAttributes:range:
-addAttribute:value:range:
-removeAttributes:range:

for example, to set a red color for the first four letters:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

There's no built-in way to draw the background color on iOS. You can create a custom string constant for the attribute, eg "MyBackgroundColorAttributeName", and then you'll have to draw it yourself.

Atka

I am using the following extension to change "NSMutableAttributedString" colour and it did the trick nicely. It can be used as a template

extension NSMutableAttributedString {

    func changeColourOf(_ terms: [String], toThisColour termsColour: UIColor, 
                        andForegroundColour fontColour: UIColor) {

        // Set your foreground Here
        addAttributes([NSAttributedString.Key.foregroundColor : fontColour], 
                      range: NSMakeRange(0, self.length))

        // Convert "NSMutableAttributedString" to a NSString  
        let string = self.string as NSString

        // Create a for loop for ther terms array
        for term in terms {
            // This will be the range of each term
            let underlineRange = string.range(of: term)

            // Finally change the term colour
            addAttribute(NSAttributedString.Key.foregroundColor, 
                         value: termsColour, 
                         range: underlineRange)
        }
    }
}

Example:

let someMutableStr = NSMutableAttributedString(string: "Hello World 2017 !")
someMutableStr.changeColourOf(["Hello", "2017"], 
                              toThisColour: .blue, 
                              theStringFontColour: .red)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!