NSString中的粗体符号

时间:2016-11-09 12:23:55

标签: ios objective-c nsstring

如何将粗体(强)设为NSString的前3个符号?例如,我有字符串@"Hello",但我需要: Hel lo

我有这个字符串:

NSString *testString = @"Hello";

2 个答案:

答案 0 :(得分:1)

您将使用此方法,其中添加原始字符串和您想要更改其字体的字符串的一部分。

这是格式化当前字符串的全局解决方案。

调用方法的语法

[self getAttributedStringWithFullString:@"Hello" forRangeOfString:@"Hel" withRangeOfStringFont:[UIFont boldSystemFontOfSize:12.0f]];





-(NSAttributedString*)getAttributedStringWithFullString:(NSString*)fullString
                                       forRangeOfString:(NSString*)rangeOfString
                                  withRangeOfStringFont:(UIFont*)rangeOfStringFont
{
    NSMutableAttributedString* att_string = [[NSMutableAttributedString alloc]initWithString:fullString];
    NSRange atRange = [att_string.string rangeOfString:rangeOfString];

    if (atRange.location != NSNotFound)
    {
        [att_string addAttribute:NSFontAttributeName value:rangeOfStringFont range:atRange];
    }

    return att_string;
}

答案 1 :(得分:0)

NSString *testString = @"Hello";

//Checking string length
if (testString.length >= 3 )
{

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

    //Bold font range
    NSRange boldFontRange = NSMakeRange(0, 3);
    [attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.0] range:boldFontRange];

    //Setting Normal Font
    NSRange normalFontRange = NSMakeRange(3, testString.length - 3);
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:normalFontRange];


    //Setting attributed Text to Label
    [self.lblTitle setAttributedText:attrString];
}