Search code examples
iosobjective-cnsstringuifontnsmutableattributedstring

How to show Bold and Italic both to My NSString without ThirdParty Libary in Objective-c


Here is my code which I attempt :

NSString *strFirst = [NSString stringWithFormat:@"The App feature is only available to users while at "];
NSString *strAreaName = kAreaName;
NSRange boldedRange = [strAreaName rangeOfString:strAreaName];

NSMutableAttributedString *newAttString = [[NSMutableAttributedString alloc] initWithString:strFirst];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:strAreaName];
UIFont *fontText = [UIFont boldSystemFontOfSize:17.0];

NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];

[newAttString appendAttributedString:attrString];

[lblFirst setAttributedText:newAttString];  

Output :
The App feature is only available to users while at America

But I want America in Bold and Italic both.

Please guide me to add in my String.

Thanks,
Mihir


Solution

  • May be you can try below code:

    //----Creating font dictionary for bold-italic text
    
    UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];
    
    UIFontDescriptor *fontDescriptorNew;
    NSDictionary *dictBoldItalicText;
    
    uint32_t NewStyles = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic;
    fontDescriptorNew = [fontDescriptor fontDescriptorWithSymbolicTraits:NewStyles];
    UIFont *updatedFont = [UIFont fontWithDescriptor:fontDescriptorNew size:17.0];//set your font size
    dictBoldItalicText = @{ NSFontAttributeName : updatedFont };
    
    //----------
    
    NSString *strFirst = [NSString stringWithFormat:@"The App feature is only available to users while at "];
    NSString *strAreaName=@"America";
    
    NSRange boldedRange = [strAreaName rangeOfString:strAreaName];
    
    NSMutableAttributedString *newAttString = [[NSMutableAttributedString alloc] initWithString:strFirst];
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:strAreaName];
    
    
    [attrString setAttributes:dictBoldItalicText range:boldedRange];//Assigning bold-italic attribute dictionary
    
    [newAttString appendAttributedString:attrString];
    
    [lblFirst setAttributedText:newAttString];
    

    Tested and working fine.