【问题标题】:hyperlink to section of text in uitextview超链接到 uitextview 中的文本部分
【发布时间】:2014-11-21 19:08:04
【问题描述】:

我正在尝试在 UITextView 上设置“常见问题”部分。如何在 UITextView 上链接一行文本,以便当用户单击它时,UITextView 滚动到同一视图中的一段文本。我还想在文本下划线并将文本颜色更改为蓝色。

【问题讨论】:

  • 你有没有尝试过?
  • 为什么要用 UITextView 来做呢? UIWebView 或 WKWebView 非常适合。
  • 我考虑将 .txt 文件加载到通过单击按钮加载的 uitextview 中。我不确定是使用 uiwebview 还是 uitextview

标签: ios xcode uitextview


【解决方案1】:

试试TTTAttributedLabel

TTTAttributedLabel 允许您自动检测日期、地址、链接、电话号码、公交信息的链接,或允许您嵌入自己的

label.enabledTextCheckingTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed
label.delegate = self; // Delegate methods are called when the user taps on a link   (see `TTTAttributedLabelDelegate` protocol)

label.text = @"Fork me on GitHub! (http://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked

NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring

【讨论】:

    【解决方案2】:

    您需要先获取文本“常见问题”的点击事件。在单击事件上,您需要编写滚动代码。

    - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
    {
    
      //Set your character range here
      //   if match  return TRUE .
      //   else    return FALSE.
    
    }
    

    在成功获取字符范围时,使用此方法将您的 textView 滚动到问题。

    CGPoint bottomOffset;
    bottomOffset = CGPointMake(0,(Y value of the question));
    [self.chatOutput setContentOffset:bottomOffset animated:YES];
    

    此方法会将 uitextview 滚动到您的问题的位置。

    【讨论】:

      【解决方案3】:
      NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
      [str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0, str.length)];
      yourTextField.attributedText = str;
      

      【讨论】:

      • 纯代码答案会自动标记为低质量,因此不鼓励在 stackoverflow 上使用。将来请用细节修饰您的答案,并解释为什么它是问题的解决方案。这有助于其他用户。
      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多