-2

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

mm24
  • 9,280
  • 12
  • 75
  • 170
  • 3
    Using `NSAttributedString` you can achieve this. – Santosh Jan 18 '17 at 15:54
  • Absolutely it is possible. Although on a word of caution from my experience, it's best to make this attributed string a generic method that can be called anywhere. Apple has been known to modify the syntax from Swift version upgrade. – user3124081 Jan 18 '17 at 16:15
  • 1
    Possible duplicate of [Bold & Non-Bold Text In A Single UILabel?](http://stackoverflow.com/questions/3586871/bold-non-bold-text-in-a-single-uilabel) – keithbhunter Jan 18 '17 at 16:45

2 Answers2

2

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
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
0

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
Sandu
  • 436
  • 4
  • 8