向UILabel的一部分添加轻击手势

我有一个NSAttributedString像这样:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"]; NSInteger length = str.length; [str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)]; 

NSMutableAttributedString被设置为一个UILabel像这样:

 label.attributedText = str; 

如何在另一个视图控制器上为上面的string中的“@clickhere”做一个点击手势(或点击)?

谢谢!

我认为,最好的方法是将UIGestureRecognizer添加到您的UILabel并validation您所需的框架。

 UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [_yourLabel addGestureRecognizer:singleTap]; - (void)handleTap:(UITapGestureRecognizer *)tapRecognizer { CGPoint touchPoint = [tapRecognizer locationInView: _yourLabel]; //Modify the validFrame that you would like to enable the touch //or get the frame from _yourLabel using the NSMutableAttributedString, if possible CGRect validFrame = CGRectMake(0, 0, 300, 44); if(YES == CGRectContainsPoint(validFrame, touchPoint) { //Handle here. } } 

只需首先为您的标签添加一个手势

 [label setUserInteractionEnabled:YES]; UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; [label addGestureRecognizer:gesture]; 

在下面的方法中控制你的手势区域

 - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer { static CGRect touchableRect = CGRectMake(100.0f, 0.0f, 100.0f, 50.0f); // Give your rect as you need. CGPoint touchPoint = [gestureRecognizer locationInView:self.view]; if (CGRectContainsPoint(touchableRect, touchPoint)) { //User has tap on where you want. Do your other stuff here } } 
  UITapGestureRecognizer *Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)]; Tap.numberOfTapsRequired = 1; // label Name Is your Label Name [labelName addGestureRecognizer:Tap]; -(void)tapDetected { //your code } 

我只想补充一下Ramshad的答案,关于如何处理有效的框架。

为此,您可能需要考虑使用UITextView而不是UILabel,而UILabel并不允许您访问如何pipe理文本的布局。 通过禁用编辑,select和滚动,UITextView的行为与UILabel大致相同,只是必须删除一些填充。

为了方便起见,您可能需要向UITextView添加一个小类,在该类中您可以编写一个方法来testing某个点是否触及范围内的任何字符。

 - (BOOL)point:(CGPoint)point touchesSomeCharacterInRange:(NSRange)range { NSRange glyphRange = [self.layoutManager glyphRangeForCharacterRange:range actualCharacterRange:NULL]; BOOL touches = NO; for (NSUInteger index = glyphRange.location; index < glyphRange.location + glyphRange.length; index++) { CGRect rectForGlyphInContainer = [self.layoutManager boundingRectForGlyphRange:NSMakeRange(index, 1) inTextContainer:self.textContainer]; CGRect rectForGlyphInTextView = CGRectOffset(rectForGlyphInContainer, self.textContainerInset.left, self.textContainerInset.top); if (CGRectContainsPoint(rectForGlyphInTextView, point)) { touches = YES; break; } } return touches; } 

这也适用于包含由于换行而跨越多行的多个单词的文本片段。 当我们处理打印的字形时,它也会处理本地化的文本。