将UITapGestureRecognizer添加到带有范围的NSAttributed Text [英] Add UITapGestureRecognizer to NSAttributed Text with a range

查看:152
本文介绍了将UITapGestureRecognizer添加到带有范围的NSAttributed Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下设置的属性字符串:

I have an attributed string set up like this:

var range = (showStr as NSString).rangeOfString(spellingStr)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen, range: range)

我想在我设置为绿色的范围内添加一个点击手势。

and i would like to add a tap gesture just to the range that i set to green.

是否有触摸属性?如何为 spellingStr 部分设置点击手势?

Is there an attribute for touches? How would i set the tap gesture just for the spellingStr part?

EDIT

EDIT

该标签和字符串的所有代码如下:

all my code for that label and string is below:

var showStr:NSString = "Showing results for \(searchT)."
println("SearchTerm:\(searchT)")
showingLabel.textColor = .blackColor()

var range = (showStr as NSString).rangeOfString(searchT)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen , range: range)

showingLabel.attributedText = attributedString
showingLabel.font = UIFont.systemFontOfSize(17)
showingLabel.numberOfLines = 0
showingLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
var showHeight:CGFloat = heightForView(showingLabel.text!, UIFont.systemFontOfSize(17), maxLabelWidth)
showingLabel.frame = CGRectMake(20, heightOfCor, maxLabelWidth, showHeight)
heightOfCor += showHeight
bgBlack.addSubview(showingLabel)


推荐答案

我是通过创建一个UIButton并将其设置为该行文本的确切框架来完成的。

I've done it by just creating a UIButton and setting it to the exact frame of that line of text.

以下是一个例子如何在objective-c中执行:

Here's an example of how to do it in objective-c:

NSRange range = [self.textView.text rangeOfString:@"The string of text you want to tap"];
self.textView.selectedRange = range;
UITextRange *textRange = [self.textView selectedTextRange];
CGRect textRect = [self.textView firstRectForRange:textRange];
CGRect convertedRect = [self.view convertRect:textRect fromView:self.textView];

UIButton *button = [[UIButton alloc]initWithFrame:convertedRect];
[button setBackgroundColor:[UIColor clearColor]];
[button addTarget:self action:@selector(textTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view bringSubviewToFront:button];

注意:在调用此函数之前,您应该已经设置了属性字符串并将其添加到您的UITextView 。此外,确保您允许在textView中进行选择(但如果您不想要高亮显示等,则禁用userInteraction)

NOTE: prior to calling this, you should have already setup your attributed string and added it to your UITextView. Also, ensure you allow selection inside your textView (but disable userInteraction if you dont want highlights etc)

这篇关于将UITapGestureRecognizer添加到带有范围的NSAttributed Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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