使NSString中的某些单词加粗并可点击标签 [英] Making certain words in an NSString bold and clickable like tags

查看:208
本文介绍了使NSString中的某些单词加粗并可点击标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让NSString中的某些单词可以点击,并且像标签一样使用不同的字体样式。

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

我有这样的代码:

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

因此上面的单词#cool和#fun将成为uibutton动作的按钮。在函数中,我将传递酷或有趣的新UIViewController。

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.

谢谢!

推荐答案

这是一段代码片段

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;






编辑

对于像这样的字符串,实现与 UIButton 类似的方法最接近的事情是首先找到使用 firstRectForRange:方法在 UITextView 中选择范围,然后覆盖实际不可见的 UIButton 连接操作。

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.

查看此答案。

这篇关于使NSString中的某些单词加粗并可点击标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆