这是要显示的文字:
© Gregory A. Dunbar <a href=\"http://gregoryadunbar.com\" rel=\"nofollow\">gregoryadunbar.com</a>\n
这是我用来显示UITextView和触发链接的代码:
此处 p.caption 是上面的字符串
textViewCaption = UITextView(frame: CGRect(x: labelPadding, y: 0.0, width: self.bounds.size.width - labelPadding * 2.0, height: self.bounds.size.height))
textViewCaption.delegate = self
textViewCaption.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textViewCaption.isOpaque = false
textViewCaption.backgroundColor = UIColor.black
textViewCaption.textAlignment = NSTextAlignment.center
textViewCaption.textColor = UIColor.white
textViewCaption.font = UIFont.systemFont(ofSize: 17.0)
textViewCaption.isEditable = false
textViewCaption.isSelectable = true
textViewCaption.dataDetectorTypes = .link
if let p = media {
let htmlData = NSString(string:String(format: "<HTML><body><font size='4'>%@</font></body></HTML>", p.caption)).data(using: String.Encoding.unicode.rawValue)
let attributedString = try! NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
textViewCaption.attributedText = attributedString
}
self.addSubview(textViewCaption)
这是检查链接的委托调用:
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL, options: [:])
} else {
UIApplication.shared.openURL(URL)
}
return true
}
注意:所有这些都在自定义视图中。
这是回复:
所以我在这里有两个问题:
- 文字未完整显示。
- 链接无法点击。
醇>
答案 0 :(得分:2)
默认情况下会阻止与http
而非https
的链接。您需要在info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>gregoryadunbar.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
或允许所有不安全的链接
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
此外,将可点击链接添加到属性字符串的方式更简单,而不是构建您可以执行的HTML
文档
let text = "your full string including link gregoryadunbar.com"
let range = text.range(of: "gregoryadunbar.com")
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.link, value: "http://gregoryadunbar.com", range: range)
attributedText.addAttribute(.font, value: someFont, range: Range(location: 0, length: text.characters.count))
attributedText.addAttribute(.foregroundColor, value: UIColor.white range: Range(location: 0, length: text.characters.count))
如果您没有设置UITextView
代理人,则默认情况下这应该有效
如果您的链接包含在a href
标记中,则可以删除链接中的所有HTML
标记,如下所示:
let link = "A. Dunbar <a href=\"http://gregoryadunbar.com\" rel=\"nofollow\">gregoryadunbar.com</a>\n"
let linkWithoutHtmlTags = link.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) // gregoryadunbar.com