重置NSMutableAttributedString字符串是不是应用了它的属性?

时间:2016-10-26 12:57:32

标签: ios objective-c

   $("div #reset-modal").off('click', "#deploy-cancel").on('click', "#deploy-cancel", function ()        {
        $(".jquery-modal.blocker.current").hide();
        $("div #reset-modal.modal").hide();
        console.log('CANCEL')
    });

    $("div #reset-modal").off('click', "#deploy-confirm").on('click', "#deploy-confirm", function () {
        $(".jquery-modal.blocker.current").hide();
        $("div #reset-modal.modal").hide();
        console.log('CONFIRM')
     });

如果我设置上面的属性字符串,则不会应用该字体。 如果我使用以下格式,我可以获得字体。

UIFont *keyFont = [UIFont fontWithName:@"Roboto-bold" size:16];
NSDictionary *keyFontDict = [NSDictionary dictionaryWithObject:keyFont forKey:NSFontAttributeName];
NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:keyFontDict];

NSString *str = @"ABC";
[titleAttrStr.mutableString setString:str];

我想只创造一次&通过重置字符串来使用attributedString。

4 个答案:

答案 0 :(得分:1)

如果在创建对象时使用非空字符串,它将按预期工作:

NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:@" " attributes:keyFontDict];

答案 1 :(得分:0)

使用工厂函数或用某些文本构建属性字符串的东西不是更好吗?

- (NSAttributedString *)attributedTextWithString:(NSString *) string {
    UIFont *keyFont = [UIFont fontWithName:@"Roboto-bold" size:16];
    // make sure to use modern Objective-C syntax too...
    NSDictionary *keyFontDict = @{NSFontAttributeName: keyFont};
    return [[NSMutableAttributedString alloc] initWithString:string attributes:keyFontDict];
}

创建字符串只是用新字符串值调用该函数的情况。

你仍然只有一个实际创建属性字符串的地方(如果你需要改变它等等)。

创建属性字符串并不足以保证只创建一次并更新它们。只需每次都刷新它。

答案 2 :(得分:0)

您可以重置旧字符串,然后重新应用属性。这仍然很昂贵,但至少您不需要重新分配NSAttributedString

[titleAttrStr replaceCharactersInRange:NSRangeFromString(titleAttrStr.string) withString:@"someNewStrig"];
[titleAttrStr setAttributes:keyFontDict range:NSRangeFromString(titleAttrStr.string)];

答案 3 :(得分:-1)

请使用此代码我的代码将为您提供帮助

NSString *strLocation = [NSString stringWithFormat:@"%@%@", @"ABC",@"DEF"];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:strLocation];
[attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName : @"Roboto-Bold" size : 16] range:NSMakeRange(0, [strLocation length])];
attributedText = [self addFont:attributedText toText:@"ABC"];
lblQue.attributedText = attributedText;

- (NSMutableAttributedString *)addFont:(NSMutableAttributedString *)attributedString toText:(NSString *)subString {
     NSRange substriingRange = [[attributedString string] rangeOfString:subString];
     [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:substriingRange]; //TextColor
     [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName : @"Roboto-Bold" size : 16] range:substriingRange]; //TextFont
     return attributedString;
}