0

如何在不添加静态范围号的情况下替换 NSMutableAttributedString 中的子字符串?我有一个带有此文本的标签:@"12 friends",一旦它将来自服务器,我想将 12(朋友的数量)替换为另一个数字(并为此子字符串使用相同的属性),并且我不能使用以下方法,因为位数未知:

/*wrong approach*/
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
[mutableAttributedString replaceCharactersInRange:NSMakeRange(0, 2) withString:counter];
[label setAttributedText:mutableAttributedString];
4

1 回答 1

1

If the label will always read "x friends" then why not just use a formatted string and pass in the number of friends as a parameter. Of course you could make this whole thing variable for localization, etc. but the basic idea is this:

NSInteger numberFromServer = ...

NSString *string = [NSString stringWithFormat:@"%d friend%@",numberFromServer,((numberFromServer != 1) ? @"s" : @"")];

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];

[label setAttributedText:attributedString];
于 2013-08-23T19:16:15.240 回答