Making certain words in an NSString bold and click

2019-06-10 19:04发布

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!

3条回答
何必那么认真
2楼-- · 2019-06-10 19:50

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:- enter image description here

查看更多
再贱就再见
3楼-- · 2019-06-10 20:02

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.

查看更多
三岁会撩人
4楼-- · 2019-06-10 20:03

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.

查看更多
登录 后发表回答