使NSString中的某些单词加粗并可点击标签
我需要让NSString中的某些单词可以点击,并且像标签一样使用不同的字体样式。
我有一个像这样的代码:
NSString *str = @"This is my string and it is #cool and #fun. Please click on the tags.";
所以上面的单词#cool和#fun将成为uibutton动作的按钮。 在函数中,我将传递酷或有趣的新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
与连接的操作重叠。
看看这个答案。
这需要是NSAttributedString,而不是NSString。 NSAttributedString允许您将样式运行应用于文本的一部分。 这样的样式运行可以包括可点击的链接。
您可以使用NSFontAttributeName
属性将字体更改为粗体变体,并且可以添加具有NSLinkAttributeName
属性的链接。
请参考以下示例代码: –
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;
输出是两个单词#cool,现在可以点击#fun,剩下的字体是粗体: –