-1

I have the following text in a UITextview

Hello! The car to your top right is where you setup your car specifications - don't worry, it takes only 30 seconds and you only ever have to set it up once!

I would like to:

  1. bold the "Hello!" and make it a size bigger to 17
  2. underline the "only 30 seconds"
  3. make the "once!" red.

How do I do this? I have very minimal knowledge with NSAttributedString and have had no luck with the documentation.

Thankyou

sathiamoorthy
  • 1,470
  • 1
  • 13
  • 23
Cescy
  • 1,731
  • 3
  • 16
  • 21

2 Answers2

2

If you want to achieve this via storyboard, select the UITextView & Goto the Attributes Inspector. then look at the below image

enter image description here

If in programmatically , Check these link && Here:

Community
  • 1
  • 1
Kumar KL
  • 15,086
  • 9
  • 36
  • 57
  • This answer is perfect! thankyou so much, I did not know you could edit it so simply like this. Quite dissappointed with the other SO memebers who just downvoted this... – Cescy Jan 31 '14 at 02:48
1

Create Mutable Attributed string, do following steps

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:yourTextView.text];

1) Found Hello! range and set font with size

NSRange foundRange = [attrString rangeOfString:@"Hello!"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute: NSFontAttributeName
                   value:[[UIFont boldSystemFontOfSize:17] fontName]
                   range:boldedRange];
    [attrString endEditing];
}

2) Search range for only 30 seconds and set underline style

foundRange = [attrString rangeOfString:@"only 30 seconds"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
    [attrString endEditing];
}

3) Search range for once! and set stroke color.

foundRange = [attrString rangeOfString:@"once!"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute:NSStrokeColorAttributeName value:[UIColor redColor] range:foundRange];
    [attrString endEditing];
}

Finally set attributed string to your textview as

yourTextView.attributedText = attrString;

Note: The above only work with ios6+..

Mani
  • 17,226
  • 13
  • 73
  • 97
  • this is great as well thankyou! but the other answer was just so much more simpler. kudos my friend – Cescy Jan 31 '14 at 02:50
  • 1
    I'm not seeing rangeOfString available to be called on an instance of NSMutableAttributedString in Swift 3 – vikzilla Jun 12 '17 at 17:49