ios - 带有 NSMutableAttributedString 的 UITextView 和 Link SwiftUI
问题描述
我有这个使用“ShouldInteractWith”方法的自定义 UITextView:
class StudyText: UITextView, UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print(URL)
return false
}
}
struct ClickableText: UIViewRepresentable {
@Binding var text: NSMutableAttributedString
func makeUIView(context: Context) -> StudyText {
let view = StudyText()
view.dataDetectorTypes = .all
view.isEditable = false
view.isSelectable = true
view.delegate = view
view.isUserInteractionEnabled = true
return view
}
func updateUIView(_ uiView: StudyText, context: Context) {
uiView.attributedText = text
}
}
我有这个扩展来设置属性文本的链接:
extension NSMutableAttributedString {
func apply(link: String, subString: String) {
if let range = self.string.range(of: subString) {
self.apply(link: link, onRange: NSRange(range, in: self.string))
}
}
private func apply(link: String, onRange: NSRange) {
self.addAttributes([NSAttributedString.Key.link: link], range: onRange)
}
}
我创建了这个布局:
struct contentView: View {
@State text: NSMutableAttributedString = NSMutableAttributedString(string: "")
var body: some View {
VStack {
ClickableText(text: self.$text)
}
.onAppear{
let myText = "Click Me!"
let attributedString = NSMutableAttributedString(string: myText)
attributedString.apply(link: "Soeme random link", subString: myText)
self.text = attributedString
}
}
}
当我单击文本视图时,它不会向控制台打印任何内容,有时它会崩溃。我怎样才能解决这个问题?
解决方案
必须提供有效的 URL,例如
let attributedString = NSMutableAttributedString(string: myText)
attributedString.apply(link: "https://www.google.com", subString: myText)
推荐阅读
- javascript - 为什么数组字面量和 BufferArray 之间的性能差距如此之大?
- haskell - 通过条件停止迭代循环并返回与条件匹配的值
- google-apps-script - 在对象 Gmail 线程中找不到函数 removeLabel
- r - 如何对LM摘要中的系数进行排序?
- python - 将现有的 NumPy 数组转换为 ctype 数组以在多处理之间共享
- python - Python logging.info 在第二次运行脚本时创建空文本文件
- html - 截断列表项内的 x-overflow
- server - 对我服务器真实 IP 的可疑请求
- ansible - 在 Jinja2 中提取嵌套对象
- arrays - 有效插入数组后查找每个元素的下限和上限