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!
Please refer the below sample code:-
Output is two word #cool and #fun is clickable now and remaining fonts are in bold:-
Here's a code snippet
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 aUITextView
using thefirstRectForRange:
method, and then overlaying an actual invisibleUIButton
with the connected action.Check out this answer.
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 theNSLinkAttributeName
attribute.