使用NSMutableAttributedString对字符串进行粗体化

时间:2016-07-20 07:08:32

标签: ios objective-c nsattributedstring nsmutableattributedstring

我使用以下代码加粗字符串的一部分。我只希望Shipment Ref. #:加粗。以下是我的代码

  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
                       value:boldFont
                       range:boldedRange];

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

问题在于它没有加粗

1 个答案:

答案 0 :(得分:2)

试试这段代码

    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];