String and attribute issues
I've dealt with this without proper results. My code looks like this
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]];
Thus, it does not highlight the username as it wishes. I tried to use NSAttributedString
for adviceString, but then I cannot use the method initWithFormat:
and list the variables after the string, and I don't see an equivalent NSAttributedString
. I wanted you NSAttributedString
instead NSMutableAttributedString
, but it doesn't seem to recognize the method addAttribute:value:fontWithName:range
. Can anyone help me? Any help is greatly appreciated.
source to share
That's for sure, you need to use NSAttributedString also adviceString
to get the attribute.
The code looks like this if you need to use stringWithFormat:
NSString *fullName = @"Anoop Kumar Vaidya";
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Hello %@", fullName]
attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]}];
In attributes, you can add multiple desired / required attributes.
EDIT 2:
You can use some methods like:
-(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]]
}];
}
And then use them as per your requirement:
NSMutableAttributedString *attributedName = [self boldString:fullName];
[attributedName appendAttributedString:[self normalString:@" is creating one"]];
[attributedName appendAttributedString:[self boldString:@" bold"]];
[attributedName appendAttributedString:[self normalString:@" string."]];
source to share