10

I am trying to decrease the size of a portion of my string and am using the below code. My output is not correct. I am only seeing my first font attribute being used for the entire string, not the specified range.

    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:title];
    NSInteger _stringLength=[descriptionText length];
    [attString addAttribute:NSFontAttributeName
                      value:[UIFont fontWithName:@"Gotham-Bold" size:20.0]
                      range:NSMakeRange(0, 10)];
    [attString addAttribute:NSFontAttributeName
                      value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0]
                      range:NSMakeRange(11, _stringLength-1)];
    [self.description setAttributedText:attString];
2
  • Is there any specific reason you're initting your string with title but you're using the length of descriptionText? Commented Jan 15, 2013 at 6:40
  • They're interchangeable, but i should use one or the other. I pass descriptionText to the method, local method variable is title. Commented Jan 15, 2013 at 13:06

4 Answers 4

6

I've had this issue too. For the second font selection you need to set the minus on the string length to be the same as where it starts.

  [attString addAttribute:NSFontAttributeName
                    value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0]
                    range:NSMakeRange(11, _stringLength-11)];

rather than:

  [attString addAttribute:NSFontAttributeName
                    value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0]
                    range:NSMakeRange(11, _stringLength-1)];
Sign up to request clarification or add additional context in comments.

Comments

4

My 2 cents ;) Swift 3

func attributedTexts(text1: String, attribs1: [String : Any]?, text2: String, attribs2: [String : Any]?) {

    let str = NSMutableAttributedString(string: text1, attributes: attribs1);
    str.append(NSAttributedString(string: text2, attributes: attribs2))

    return str
}

Usage:

let attr1 = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 24)]
let attr2 = [NSFontAttributeName: UIFont.systemFont(ofSize: 16)]
let attributedString = self.attributedTexts(text1: "First Text", attribs1: attr1, text2: "\nSecond Text", attribs2: attr2)

Comments

0

There is nothing wrong with your code. Possibly you are trying to use font names that don't exist. Did you check that the fonts actually exist, e.g. by po or NSLog?

What's the output if you log the attributedString?

Comments

0

Please have a look at this site and video, you may get something usefull

Rich text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.