How do you use NSAttributedString?

后端 未结 15 966
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题