2015-04-22 103 views
1

在我的应用程序中,我从服务器上的文本文件中读取数据。当我得到这个NSString时,我想基本上让它的不同部分可点击,这样如果他们点击某个句子,它就会打开一个对话框。我将如何去做这件事?使NSString的不同部分可点击

我已阅读关于使用UITapGestureRecognizer,但我不知道如何使用它来识别一个文本字符串,而不是一次一个单词。

我也看过NSMutableAttributedStrings,但我只是没有找到我需要了解如何做到这一点。

任何帮助,将不胜感激。

+0

你有没有读过[SO问题](http://stackoverflow.com/questions/21629784/make-a-clickable-link-in-an-nsattributedstring-for-a-uitextfield-or-uilabel)? – Azat

+0

@Azat那些使用URL,我不知道如何使用方法调用。 – saboehnke

+0

你的根本错误是'NSString'和'NSAttributedString'都没有UI部分,用户不能与它们交互。所以一般来说,你当前问题表述的答案是“这是不可能的”。然而,如果你通过添加你如何显示它,在UILabel,UITextView,通用UIView或其他方式来澄清它,你可能会得到合理的答案 – Azat

回答

0

您可以使用NSAttributedString插入具有自定义URL方案的链接。然后,当您检测到链接已被按下时,请检查url方案,如果它是您的,请按照该方法执行任何您想要的操作。你将不得不使用UITextView,或者你也可以使用TTTAttributedLabel(你可以找到TTTAttributedLabelhere)。以下示例代码(灵感来自较早的Ray Wenderlich文章)使用UITextView

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Something should happen when you press _here_"]; 
[attributedString addAttribute:NSLinkAttributeName 
         value:@"yoururlscheme://_here_" 
         range:[[attributedString string] rangeOfString:@"_here_"]]; 

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor], 
          NSUnderlineColorAttributeName: [UIColor lightGrayColor], 
          NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)}; 

// assume that textView is a UITextView previously created (either by code or Interface Builder) 
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links 
textView.attributedText = attributedString; 
textView.delegate = self; 

然后,为了真正赶上链路上的水龙头,实现以下UITextViewDelegate方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { 
    if ([[URL scheme] isEqualToString:@"yoururlscheme"]) { 
     NSString *tappedWord = [URL host]; 
     // do something with this word, here you can show your dialogbox 
     // ... 
     return NO; // if you don't return NO after handling the url, the system will try to handle itself, but won't recognize your custom urlscheme 
    } 
    return YES; // let the system open this URL 
} 

我发现UITextViewNSAttributedString以及自定义网址是相当强大的,你可以做很多的与他们的事情,你也可以通过你的网址发送参数,有时可以很方便。

您可以将url方案更改为在您的情况下更有意义(而不是yoururlscheme)。只要确保在创建URL时以及处理它时检查url方案就可以对其进行更改。例如,如果你想在你的文本视图中点击文本时有多个行为,你也可以有多个url方案。

+0

我给了一个镜头,但现在我有一个错误,说:沿着以下方向:从不兼容的类型分配给'id uitextviewdelegate'。我已经进入了我的视图控制器头,并添加了但没有运气。 – saboehnke