Making text bold using attributed string in swift

2019-01-03 09:01发布

I have a string like this

var str = "@text1 this is good @text1"

Now replace text1 with another string, say t 1. I am able to replace the text, but i am not able to bold it. I want to bold the new string t 1, so that the final output will be:

@t 1 this is good @t 1

How can I do it?

All the examples I am seeing are in Objective-C, but I want to do it in Swift.

Thanks in advance.

14条回答
乱世女痞
2楼-- · 2019-01-03 09:44

Just use code something like this:

 let font = UIFont(name: "Your-Font-Name", size: 10.0)!

        let attributedText = NSMutableAttributedString(attributedString: noteLabel.attributedText!)
        let boldedRange = NSRange(attributedText.string.range(of: "Note:")!, in: attributedText.string)
        attributedText.addAttributes([NSAttributedString.Key.font : font], range: boldedRange)
        noteLabel.attributedText = attributedText
查看更多
Melony?
3楼-- · 2019-01-03 09:47

edit/update: Xcode 8.3.2 • Swift 3.1

If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:

extension String {
    var html2AttStr: NSAttributedString? {
        return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
    }
}

"<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr
查看更多
登录 后发表回答