Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bold some words in my UITextView using NSMutableAttributedString?

I have a UITextView and there are certain words I'm casting with NSString stringWithFormat that I'd like to be bolded.

I have looked around Stack Overflow and tried to follow the the postings but I guess I'm not understanding it.

Here's what I've been playing around with:

    NSRange boldedRange = NSMakeRange(0, 4);
    NSString *boldFontName = [[UIFont fontWithName:@"Helvetica-Bold" size:100]fontName];


    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.name];

    [attrString beginEditing];
    [attrString addAttribute:NSFontAttributeName
                       value:boldFontName
                       range:boldedRange];
    [attrString endEditing];

    self.resultsTextView.attributedText = attrString;


    self.resultsTextView.text = [NSString stringWithFormat:@"One day, %@ was taking a walk and saw a %@ boy.  He was %@ a %@.", attrString, self.adjective, self.adverb, self.noun];
like image 794
May Yang Avatar asked Jan 17 '15 07:01

May Yang


2 Answers

You can also set it the following way if you want by setting a dictionary as a whole, as attribute

NSString *strTextView = @"This is some demo Text to set BOLD";

NSRange rangeBold = [strTextView rangeOfString:@"BOLD"];

UIFont *fontText = [UIFont boldSystemFontOfSize:10];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];

NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:strTextView];
[mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];

[textViewTermsPolicy setAttributedText:mutAttrTextViewString];
like image 181
channi Avatar answered Oct 21 '22 09:10

channi


Use the below code to set Attribute string in TextView.

    NSString *infoString =@"I am Kirit Modi from Deesa.";

    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];

    UIFont *font_regular=[UIFont fontWithName:@"Helvetica" size:20.0f];
    UIFont *font_bold=[UIFont fontWithName:@"Helvetica-Bold" size:20.0f];

    [attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(0, 4)];

    [attString addAttribute:NSFontAttributeName value:font_bold range:NSMakeRange(5, 15)];

    [attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(16, infoString.length - 15 - 1)];

    [self.txtView setAttributedText:attString];

OutPut :

enter image description here

like image 41
Kirit Modi Avatar answered Oct 21 '22 10:10

Kirit Modi