I was wondering if it was possible to bold specific words within a text that is being held in an NSString. I am able to bold, change the font of characters based on their location within the string using NSMutableAttributedString like this:
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:utf8String];
UIFont *boldFont = [UIFont boldSystemFontOfSize:18];
NSRange boldedRange = NSMakeRange(0, 9);
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFont
range:boldedRange];
[attrString endEditing];
But this changes the font of the first 9 characters in the String.
What I want is to put in Bold the following words should they be found within the string: "Questions", "Did you know" and "Further reading". Is this possible? The fact is that I don't know their position in the string.
I did have a look at the question suggesting this is a duplicate, but my question is not exactly the same and the answers provided did not help. I Need to find ranges within a string and then add them to an NSMutableAttributedString, and this is the bit I am asking help for. An answer has been provided that explains how to do that.
EDIT: The supposed duplicate and its answer DO NOT answer the question. This question is more than just finding specific words within a paragraph, it is also about how to format them using NSMutableAttributedString. The answer provided below is the answer. Thanks!
If you don't know substring position then you can use NSRange to find position of substring and using position you can make changes to the substring using NSMutableAttributedString class. example :
UIFont *fontForlabel1 = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
UIFont *fontForlabel2 = [UIFont fontWithName:@"Helvetica-Bold" size:19.0];
UIFont *fontForlabel3 = [UIFont fontWithName:@"Helvetica" size:12.0];
NSString *text = @"Do you know that or did you know that?";
NSRange range;
UILabel *setlable;
NSMutableAttributedString * attributedString= [[NSMutableAttributedString alloc] initWithString:text];
range = [text rangeOfString:@"Do you know"];
[attributedString addAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:fontForlabel1} range:range];
range = [text rangeOfString:[@"or"];
[attributedString addAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:fontForlabel2} range:range];
range = [text rangeOfString:@"did you know that"];
[attributedString addAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:fontForlabel3} range:range];
setlable.attributedText=attributedString;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments