18

I am digging into NSAttributedStrings on iOS. I have a model that is returning a persons first and last name as NSAttributesString. (I don't know if it is a good idea to deal with attributed strings in models!?) I want the first name to be printed regular where as the last name should be printed in bold. What I don't want is to set a text size. All I found so far is this:

- (NSAttributedString*)attributedName {
    NSMutableAttributedString* name = [[NSMutableAttributedString alloc] initWithString:self.name];
    [name setAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]} range:[self.name rangeOfString:self.lastname]];
    return name;
}

However, this will, of course, override the font size of the last name, which gives a very funny look in a UITableViewCell where the first name will be printed in the regular text size of the cell's label and the last name will be printed very small.

Is there any way to achieve what I want?

Thanks for your help!

4

6 に答える 6

3

この質問のテクニックを使用してください:

UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];
uint32_t existingTraitsWithNewTrait = UIFontDescriptorTraitBold;
    fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
UIFont *updatedFont = [UIFont fontWithDescriptor:fontDescriptor size:0.0];
NSDictionary *attribs =  @{NSFontAttributeName : updatedFont};
[mutableAttrString setAttributes:attribs range:result.range];
于 2015-04-03T04:31:51.643 に答える