【问题标题】:Clickable URL in NSMutableAttributedString iOS6NSMutableAttributedString iOS6 中的可点击 URL
【发布时间】:2012-10-24 19:22:11
【问题描述】:

我正在开发一个有趣的应用程序,我可以在其中接收来自远程 Web 服务(如 Twitter)的消息。有时这些消息包含 URL:s,我想让这些消息可点击。我想知道哪种方法是最好的。我试过 NSLinkAttributeName 但它不适用于 iOS。是否可以创建一个透明按钮并将其放置在文本视图中正确位置的上方?我怎么能这样做?还是有更好/更简单的方法? url 的位置和长度可以变化。

【问题讨论】:

    标签: objective-c ios ios6


    【解决方案1】:

    有两种很好的方法来解决这个问题:

    1. CoreText,或者更确切地说是围绕它的包装器,例如 TTTAtributedLabel

    这是最强大的解决方案。它支持 Datadetectortypes(尽管您最好在显示它之前进行自己的性能检测)并且它相对流行。

    但是,根据您的使用情况,它可能会影响您的 tableview 的滚动性能。

    2。在标签上方动态放置按钮,例如 IFTweetLabel

    这是一个简单的解决方案。 IFTweetLabel 基本上是 UILabel 的一个插件,它开箱即用的性能非常好。但是,如果您希望对其进行过多的自定义,您最终会遇到它的限制。更不用说它在 100% 的时间里都表现得不完美。 YMMV。

    【讨论】:

    • 谢谢,决定使用 TTTAtributedLabel。
    【解决方案2】:

    一种选择是使用UIDataDetectorTypeLink。检查这个link for more details.

    // Create textview, centering horizontally
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 10, 320, 50)];
    
    // Set font, background and alignment
    [textView setFont:[UIFont boldSystemFontOfSize:16]];
    [textView setBackgroundColor:[UIColor blackColor]];
    [textView setTextAlignment:UITextAlignmentCenter];
    
    // Unfortunately the link will show as blue even with this setting
    //  [textView setTextColor:[UIColor greenColor]];
    
    // Edit and scrolling off  
    [textView setEditable:NO];
    [textView setScrollEnabled:NO];
    
    // Set data type to specify URL/link
    [textView setDataDetectorTypes:UIDataDetectorTypeLink];
    
    // Set text as URL
    [textView setText:@"text.com"];  
    
    [self.view addSubview:textView];
    

    其他一些选项是UIWebview,其中代表处理对其中的 url 的触摸。另一个选项是fancy UILabels

    对于您提出的其他问题,请查看How to open a UITextView URL in UI Web View?Is there a way to create custom UIDataDetectorTypes?Change color of UITextView links with a filter?

    【讨论】:

    • 谢谢,UIDataDetectorTypeLink 似乎适用于链接。但我想知道是否可以改变链接的外观,或者更具体地说是颜色。并且还进行更改,使其在自定义 UIWebView 而不是 Safari 中打开?是否可以通过继承 UITextView 来制作自定义 UIDataDetectorTypes,例如 @mentions 和 #hashtags。
    • 检查这个,stackoverflow.com/questions/1555294/…stackoverflow.com/questions/2358343/…,并使用过滤器更改 UITextView 链接的颜色? .. 我已经用这些链接更新了我的答案。
    【解决方案3】:

    NSLinkAttributeName 可以与 UITextView 一起点击,但不能与 UILabel 一起点击。请注意 it's for iOS 7+,并且 UITextView 必须是 Selectable(在 Storyboard 中)。

    Swift 演示:

    let attributedText = NSMutableAttributedString(string: "Hello world")
    attributedText.addAttribute(.link, value: URL(string: "https://example.com")!, range: NSRange(location: 0, length: attributedText.length))
    textView.attributedText = attributedText
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 2015-07-17
      • 2013-02-07
      • 2019-05-07
      相关资源
      最近更新 更多