我实际上是将网站中的一些页面克隆到UITextViews中。我将它们设置为归因于文本,因此当我从网站粘贴文本时,它会保留它的大小和字体。但是,许多页面包含未被识别为链接的超链接单词(如“单击此处”)。
我尝试从文本视图中提取文本(我将其粘贴到故事板中),将其转换为NSMutableAttributedString,将超链接添加为范围内的属性,然后转换回NSAttributedString并将其设置为TextView的文本。问题是,范围很奇怪。例如,这里是0-5的范围(看左上角): Range from 0-5 并且范围为8-10 Range from 8-10 我需要它来申请“'我现在可以做些什么来帮助?'”。任何关于如何使这项工作的建议将不胜感激。这是我的代码:
import UIKit
class ApproachController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textBox: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.textBox.delegate = self
let text = textBox.attributedText.mutableCopy() as! NSMutableAttributedString
text.addAttribute(NSLinkAttributeName, value: "https://campushealth.unc.edu/services/counseling-and-psychological-services/how-support-student-distress/what-can-i-do-right-now", range: NSMakeRange(8, 10))
self.textBox.attributedText = text.copy() as! NSAttributedString
}
答案 0 :(得分:1)
您可以指定子字符串的使用范围,如:
let strMsg : NSString = "By registering you agree to our Terms & Condtions & Privacy Policy" - Replace this with your textBox.text
attrMsg.addAttribute(NSLinkAttributeName, value: "http://www.seqlegal.com/free-legal-documents/website-terms-and-conditions", range: strMsg.range(of: "Terms & Condtions"))
textBox.attributedText = attrMsg
答案 1 :(得分:1)
有了user3575114的帮助,我就明白了。这是我的更正代码,因为任何人都有同样的问题:
override func viewDidLoad() {
super.viewDidLoad()
self.textBox.delegate = self
let strang = textBox.text! as NSString
let text = textBox.attributedText.mutableCopy() as! NSMutableAttributedString
text.addAttribute(NSLinkAttributeName, value: "https://campushealth.unc.edu/services/counseling-and-psychological-services/how-support-student-distress/what-can-i-do-right-now", range: strang.range(of: "What can I do now to help?"))
textBox.attributedText = text
}