2016-02-03 22 views
2

我有一个这样的字符串,显示字符串作为UIWebView中的链接 - 斯威夫特

无功海峡=“你好,去http://stackoverflow.com

,我想显示此字符串中一个UIWebView ,因此http://stackoverflow.com将显示为链接。

为此,我使用了UIWebView的loadHtmlString

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

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

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

有没有什么办法可以解析并显示文本作为UIWebView中的链接?

+2

使用是否需要将字符串显示在'UIWebView' ?您可以在禁用编辑并启用链接检测的情况下在“UITextView”中显示它 –

+1

是的。因为我也在显示图像。 –

+2

@DeepikaMasilamani然后我推荐使用正则表达式('NSRegularExpression')并用''标签包装的字符串替换匹配的字符串 –

回答

4

dataDetectorTypes设置为UIWebView上的链接。这是在操场的例子可以运行和查看:

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功能,你只是tyring显示的链接,那么你应该使用UITextView这也支持dataDetectorTypes

+0

非常感谢您的回应..它的工作原理! –

+0

我也显示图像..所以我不能使用UITextView。 –

+0

有帮助的回答 - upvoted,我收藏这个以备后用。谢谢Joe – NSPratik

2

@乔的回答看起来也不错,这里是另一种解决方案

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

+0

非常感谢这个解决方案。我也会尝试使用这个,以了解NSDataDetector。 –