How do you use NSAttributedString?

后端 未结 15 937
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:19

Multiple colours in an NSString or NSMutableStrings are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit

相关标签:
15条回答
  • 2020-11-22 04:52

    You can load an HTML attributed string in Swift as follow

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

    To load a html from file

       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

    And setup string as per your required attribute....follow this..
    http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/

    0 讨论(0)
  • 2020-11-22 04:54

    I wrote helper to add attributes easily:

    - (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

    You can install through CocoaPods also : pod 'MASAttributes', '~> 1.0.0'

    0 讨论(0)
  • 2020-11-22 04:54

    An easier solution with attributed string extension.

    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)
        }
    
    }
    

    Try this and see (Tested in 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)
    

    Here is expected result:

    enter image description here

    0 讨论(0)
  • 2020-11-22 04:54

    Super easy way to do this.

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

    For more detail click here; https://github.com/iOSTechHub/AttributedString

    0 讨论(0)
  • 2020-11-22 05:00

    To solve such kind of problems I created library in swift which is called 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
    

    You can find it here https://github.com/psharanda/Atributika

    0 讨论(0)
  • 2020-11-22 05:02

    I made a library that makes this a lot easier. Check out ZenCopy.

    You can create Style objects, and/or set them to keys to reference later. Like this:

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

    Then, you can easily construct strings AND style them AND have params :)

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

    You can also style things easily with regex searches!

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

    This will style all words with '@' in front of it with the 'token' style. (e.g. @jpmcglone)

    I need to still get it working w/ everything NSAttributedString has to offer, but I think fontName, fontSize and color cover the bulk of it. Expect lots of updates soon :)

    I can help you get started with this if you need. Also looking for feedback, so if it makes your life easier, I'd say mission accomplished.

    0 讨论(0)
提交回复
热议问题