检测 iOS 中 UITextView 中属性文本的点击 [英] Detecting taps on attributed text in a UITextView in iOS
问题描述
我有一个 UITextView
,它显示一个 NSAttributedString
.这个字符串包含我想让它成为可点击的单词,这样当它们被点击时,我会被回调,以便我可以执行一个操作.我意识到 UITextView
可以检测对 URL 的点击并回调我的委托,但这些不是 URL.
I have a UITextView
which displays an NSAttributedString
. This string contains words that I'd like to make tappable, such that when they are tapped I get called back so that I can perform an action. I realise that UITextView
can detect taps on a URL and call back my delegate, but these aren't URLs.
在我看来,有了 iOS 7 和 TextKit 的强大功能,这现在应该是可能的,但是我找不到任何示例,也不知道从哪里开始.
It seems to me that with iOS 7 and the power of TextKit this should now be possible, however I can't find any examples and I'm not sure where to start.
我知道现在可以在字符串中创建自定义属性(虽然我还没有这样做),也许这些对于检测是否已经点击了一个魔术词很有用?无论如何,我仍然不知道如何拦截那个点击并检测点击发生在哪个单词上.
I understand that it's now possible to create custom attributes in the string (although I haven't done this yet), and perhaps these will be useful to detecting if one of the magic words has been tapped? In any case, I still don't know how to intercept that tap and detect on which word the tap occurred.
请注意,不需要兼容 iOS 6.
Note that iOS 6 compatibility is not required.
推荐答案
我只是想多帮助别人一点.根据 Shmidt 的回答,可以完全按照我在原始问题中的要求进行操作.
I just wanted to help others a little more. Following on from Shmidt's response it's possible to do exactly as I had asked in my original question.
1) 创建一个属性字符串,其中自定义属性应用于可点击的词.例如.
1) Create an attributed string with custom attributes applied to the clickable words. eg.
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"a clickable word" attributes:@{ @"myCustomTag" : @(YES) }];
[paragraph appendAttributedString:attributedString];
2) 创建一个 UITextView 来显示该字符串,并向其添加一个 UITapGestureRecognizer.然后处理水龙头:
2) Create a UITextView to display that string, and add a UITapGestureRecognizer to it. Then handle the tap:
- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
UITextView *textView = (UITextView *)recognizer.view;
// Location of the tap in text-container coordinates
NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [recognizer locationInView:textView];
location.x -= textView.textContainerInset.left;
location.y -= textView.textContainerInset.top;
// Find the character that's been tapped on
NSUInteger characterIndex;
characterIndex = [layoutManager characterIndexForPoint:location
inTextContainer:textView.textContainer
fractionOfDistanceBetweenInsertionPoints:NULL];
if (characterIndex < textView.textStorage.length) {
NSRange range;
id value = [textView.attributedText attribute:@"myCustomTag" atIndex:characterIndex effectiveRange:&range];
// Handle as required...
NSLog(@"%@, %d, %d", value, range.location, range.length);
}
}
当你知道怎么做的时候很容易!
So easy when you know how!
这篇关于检测 iOS 中 UITextView 中属性文本的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!