Is it possible to selectively change the font in parts of a UITextView ?
I have got a UITextView and would like to selectively change the font size and style for parts of it. For example
Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam
You can use NSAttributedString
to give attributes on string using addAttribute method.
let string = "Bold Italics Roman"
let attributes = [NSFontAttributeName: UIFont(name: "Open Sans", size: 18.0)!]
let attributedText = NSMutableAttributedString(string: string, attributes: attributes)
let sampleString = string as NSString
let range = sampleString.range(of: "Italics")
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "OpenSans-Italic", size: 18.0)!, range: range)
textView.attributedText = attributedText
we can achieve this using NSString and attribute with the rangeofString: method
let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar"
let longestWord = "VeryLongWord"
let longestWordRange = (longString as NSString).rangeOfString(longestWord)
let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)])
attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange)
label.attributedText = attributedString
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.