ios - 无法获取 url 的下划线并检测 url 后的空格

标签 ios swift

我编写了这段代码来检测 url...即如果我在 TextView 中输入一个网址,那么它应该检测到该网址并显示一条消息。这段代码是在textview中写的shouldChangeTextIn range....

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    if textView == contributeTextView {

      let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
      let matches = detector.matches(in: textView.text, options: [], range: NSRange(location: 0, length: textView.text.utf16.count))

      for match in matches {
        guard let range = Range(match.range, in: textView.text) else { continue }
         url = textView.text[range]
        print("THIS IS THE URL:-> \(url)")
      }
       return true
    }

    //CODE TO GET URL AS UNDERLINED

      .......

    return true
  }

这段代码运行良好。但如果它是一个 url,那么我还希望在该 url 下方显示一条下划线以表明它是一个 url。为此,我编写了以下代码...

  //CODE TO GET URL AS UNDERLINED
   let attributedString = NSMutableAttributedString(string: textView.text)
  let range = (textView.text as NSString).range(of: "\(url)")
  attributedString.addAttribute(.link, value: "\(url)", range: range)

  textView.attributedText = attributedString

但是它不起作用。出了什么问题...? 另外,如果我写下整个网址并按空格,我在哪里可以知道空格已被按下...?

最佳答案

您的代码无法正常工作的原因是 addAttributevalue 错误。这是正确的片段。

 let attributedString = NSMutableAttributedString(string: textView.text)
  let range = (textView.text as NSString).range(of: "\(url)")
  attributedString.addAttribute(.link, value: 1, range: range)
  attributedString.addAttribute(.underlineStyle, value: 1, range: range)
  attributedString.addAttribute(.underlineColor, value: UIColor.blue, range: range)

  textView.attributedText = attributedString

enter image description here

关于ios - 无法获取 url 的下划线并检测 url 后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390084/

相关文章:

ios - 如何将 subview 添加到 TableView 单元格中的stackview?

ios - 将 UIView 在其父 View 中垂直和水平居中

ios - 获取 Sprite 在另一个类中的位置

ios - 从 HTTP JSON 树中接收特定信息

swift - 来自 JSON 的 Realm 数据库中的条目

iphone - iOS CoreImage 边缘检测

ios - UITableViewCell 缩进时髦

swift - 嵌入式 TableViewController 上未显示导航栏 - Swift

swift - ( cocoa 错误-1)尝试保存使用 AVCaptureSession 创建的视频时

ios - ViewController 的释放