字符串和归因问题

时间:2014-12-10 11:21:52

标签: ios nsstring nsattributedstring

我一直在弄乱这个没有正确结果。我的代码如下

NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc]initWithString:((User *)appDelegate.users[self.currentUserIndex]).name];
[nameString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:NSMakeRange(0, nameString.length)];

NSString *adviceString = [[NSString alloc] initWithFormat:@"%@, remember be extra aware of the \n cat today. The dog index is 4, dogcatcher \n suggests you should at minimum wear \n a dog and apply cat...", [nameString string]];

因此,它不会根据需要加粗用户名。我尝试将NSAttributedString用于adviceString但是我不能使用initWithFormat:方法并在字符串后面列出变量,我没有看到任何NSAttributedString等价物。我想要NSAttributedString代替NSMutableAttributedString,但它似乎无法识别addAttribute:value:fontWithName:range方法。有人可以帮帮我吗?任何帮助非常感谢。

1 个答案:

答案 0 :(得分:0)

这是肯定的,你还需要使用NSAttributedString来adviceString来获取属性。

如果您需要使用stringWithFormat:

,代码就是这样的
NSString *fullName = @"Anoop Kumar Vaidya";
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Hello %@", fullName]
                                       attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]}];

在属性中,您可以添加更多所需/必需的属性。

编辑2:

您可能希望使用以下方法:

-(NSMutableAttributedString *)normalString:(NSString *)string{
    return [[NSMutableAttributedString alloc] initWithString:string
                                                  attributes:@{}];
}

-(NSMutableAttributedString *)boldString:(NSString *)string{
    return [[NSMutableAttributedString alloc] initWithString:string
                                                  attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]
                                                               }];
}

然后根据您的要求使用它们:

NSMutableAttributedString *attributedName = [self boldString:fullName];
[attributedName appendAttributedString:[self normalString:@" is creating one"]];
[attributedName appendAttributedString:[self boldString:@" bold"]];
[attributedName appendAttributedString:[self normalString:@" string."]];