Making certain words in an NSString bold and click

2019-06-10 19:22发布

问题:

I need to make certain words in a NSString be clickable and a different font style like a tag would.

I have a code like so:

NSString *str = @"This is my string and it is #cool and #fun.  Please click on the tags.";

So the above word #cool and #fun would become buttons to a uibutton action. In the function I would pass cool or fun to a new UIViewController.

Thanks!

回答1:

Here's a code snippet

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
[str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0,str.length)];
[str addAttribute:kCTFontAttributeName value: boldFontName range: NSMakeRange(0,str.length)];
yourTextField.attributedText = str;

Edit

The closest thing to implementing methods similar to UIButton action for a string like this would be to first find the rect of the selected range in a UITextView using the firstRectForRange: method, and then overlaying an actual invisible UIButton with the connected action.

Check out this answer.



回答2:

This would need to be an NSAttributedString, not an NSString. An NSAttributedString lets you apply a style run to just one part of the text. And such a style run can include a clickable link.

You can change the font to a bold variant with the NSFontAttributeName attribute, and you can add the link with the NSLinkAttributeName attribute.



回答3:

Please refer the below sample code:-

NSString *str = @"This is my string and it is #cool and #fun.  Please click on the tags.";
NSMutableAttributedString *yourAtt=[[NSMutableAttributedString alloc]init];
for (NSString *word in [str componentsSeparatedByString:@" "])
{
    if ([word isEqualToString:@"#cool"] || [word isEqualToString:@"#fun."])
    {
     [yourAtt appendAttributedString:[[NSAttributedString  alloc]initWithString:word attributes:@{NSLinkAttributeName:@"http://www.google.com"}]];
    }
    else
    {
     [yourAtt appendAttributedString:[[NSAttributedString  alloc]initWithString:word attributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:12]}]];
    }
    [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@" "]];
}
self.yourAttStr=yourAtt;

Output is two word #cool and #fun is clickable now and remaining fonts are in bold:-