【问题标题】:Displaying string as link in UIWebview - Swift在 UIWebview 中将字符串显示为链接 - Swift
【发布时间】:2016-05-12 17:57:29
【问题描述】:

我有一个这样的字符串,

var str = "你好,去http://stackoverflow.com"

我想在 UIWebView 中显示此字符串,以便 http://stackoverflow.com 将显示为链接。

为此,我使用 UIWebView 的loadHtmlString

但文本不显示为链接。它在 UIWebView 中显示为普通文本。

经过一番研究,我发现问题是missing of <a href = ""></a> tag

对于静态字符串,我可以手动将标签添加到字符串中。但我从 http 响应中获取字符串。所以我不知道如何在适当的索引中添加<a> 标签。

有什么方法可以解析文本并将其显示为 UIWebView 中的链接?

【问题讨论】:

  • 是否要求字符串显示在UIWebView中?您可以在 UITextView 中显示它,并禁用编辑并启用链接检测
  • 是的..因为我也在显示图像。
  • @DeepikaMasilamani 然后我推荐使用正则表达式 (NSRegularExpression) 并将匹配的字符串替换为 <a> 标签包裹的字符串
  • 感谢您的建议。我可以获得任何使用 NSRegularExpression 的示例代码吗?我不习惯NSRegularExpression。这就是为什么,如果我得到任何链接来了解它,那么它会对我有所帮助。

标签: ios swift uiwebview


【解决方案1】:

在 UIWebView 上将 dataDetectorTypes 设置为 Link。这是一个可以在 Playground 中运行和查看的示例:

import UIKit
import XCPlayground

let str = "Hello, go to http://stackoverflow.com"
let webview = UIWebView(frame: CGRect(x: 0, y: 0, width: 200.0, height: 200.0))
webview.dataDetectorTypes = .Link
webview.loadHTMLString(str, baseURL: nil)

XCPlaygroundPage.currentPage.liveView = webview

如果您的内容不依赖任何 HTML 功能并且您只是想显示链接,那么您应该使用UITextView,它也支持dataDetectorTypes

【讨论】:

  • 我也在显示图像。所以我不能使用 UITextView。
  • 有用的答案 - 赞成,我收藏了这个以备后用。谢谢乔
【解决方案2】:

@Joe 的回答看起来也不错,这里有另一个解决方案

let str = "Hello, go to http://stackoverflow.com or to http://example.com "

let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)

let matches = detector.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))

var newStr = str
for match in matches {
    let url = (str as NSString).substringWithRange(match.range)
    newStr = newStr.stringByReplacingOccurrencesOfString(url, withString: "<a href='\(url)'>\(url)</a>")

}

print(newStr)

这会修改字符串,然后在UIWebView中使用

【讨论】:

  • 非常感谢这个解决方案。我也会尝试这个,以了解 NSDataDetector。
猜你喜欢
  • 2020-12-04
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多