Learner Learner - 1 year ago 78
Objective-C Question

Bolding a string using NSMutableAttributedString

Im using the following code to bold a part of string. I want only the

Shipment Ref. #:
to be bolded. Following is my code

UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = [NSString stringWithFormat:@"Shipment Ref. #: %@ ",[[[NSUserDefaults alloc] init] valueForKey:@"shipRef"]];
NSRange boldedRange = NSMakeRange(10, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName

[attrString endEditing];
self.shipRefHeader.text = [attrString mutableString];

The problem is that it is not getting bolded

Answer Source

try this code

    NSString * yourString = [NSString stringWithFormat:@"Shipment Ref. #: %@ ",[[[NSUserDefaults alloc] init] valueForKey:@"shipRef"]];;
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
    NSString *boldString = @"Shipment Ref. #:";
    NSRange boldRange = [yourString rangeOfString:boldString];
    [attrString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:boldRange];
    [self.shipRefHeader setAttributedText: attrString];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download