【问题标题】:Perform action by clicking on some word in Uitextview or UILabel通过单击 Uitextview 或 UILabel 中的某个单词来执行操作
【发布时间】:2014-03-12 00:35:58
【问题描述】:

当用户单击 Uitextview(或 UIlabel)中的某些格式化/特定单词时,我该如何执行某些特定操作(例如显示模式或推送控制器)? 我听说过 NSAttributedString,但我不确定如何使用它。

我想要的是与 facebook 应用程序相同的结果。当您单击一个名称时,它会推送另一个控制器:

如果你能给我一些提示、教程或任何你想要的东西。

【问题讨论】:

标签: ios iphone cocoa-touch ios7


【解决方案1】:

将手势识别器添加到您的 UITextView:

//bind gesture
[_yourTextView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:delegate action:@selector(didReceiveGestureOnText:)]];

然后只需使用以下代码检查在 didReceiveGestureOnText 中单击了哪个单词:

+(NSString*)getPressedWordWithRecognizer:(UIGestureRecognizer*)recognizer
{
    //get view
    UITextView *textView = (UITextView *)recognizer.view;
    //get location
    CGPoint location = [recognizer locationInView:textView];
    UITextPosition *tapPosition = [textView closestPositionToPoint:location];
    UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];

    //return string
    return [textView textInRange:textRange];
}

编辑

这就是你的 didReceiveGestureOnText 方法的样子:

-(void)didReceiveGestureOnText:(UITapGestureRecognizer*)recognizer
{
    //check if this is actual user
    NSString* pressedWord = [delegate getPressedWordWithRecognizer:recognizer];
}

然而,这将引导你检查字符串,毕竟这真的很酷(因为它很慢)。

【讨论】:

  • 这个回复被严重低估了!
  • 效果很好,但要改进,请参阅this 回答
【解决方案2】:

这很老套,但您可以尝试使用 TTTAttributedLabel 并将自定义 URL 附加到标签中的单词/短语:

    TTTAttributedLabel *label;
    //after setting the label text:
    [label addLinkToURL:[NSURL URLWithString:@"http://www.stackoverflow.com"] withRange:[label.text rangeOfString:@"CLICKABLE TEXT HERE"]];

然后在委托方法中,调用您选择的操作:

#pragma mark - TTTAttributedLabelDelegate

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    // for handling the URL but we just call our action
    [self userHasClickedTextInLabel];
}

【讨论】:

    【解决方案3】:

    您可以向标签添加手势识别器。例如:

    [yourLabel setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelButton:)];
    [tapGestureRecognizer setNumberOfTapsRequired:1];
    [yourLabel addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    

    您没有指定您正在使用哪个版本,或者它是通过 IB 还是以编程方式。这会在您的标签上设置手势识别器。选择器是您要执行的操作,例如 performSegue 等。让我知道这是怎么回事

    【讨论】:

    • 我使用的是 ios 7 和 xcode 5。不管是通过 IB 还是以编程方式。您的示例适用于整个标签。如果我在标签中有如下文本:“这是我的带有 [word1] 和 [word2] 的示例”。我想将我点击的单词(word1 或 word2)发送到我的选择器,但如果用户点击其他任何内容,我不想执行任何操作。
    • 嗯,我明白你的意思了。您最初的问题并不清楚,但我认为您应该研究类似 NSAttributedString 的内容。确切地说他不确定我害怕,但我会调查一下,因为看到这个解决方案会很有趣
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多