gpt4 book ai didi

ios - UITextView 与 NSMutableAttributedString 与链接 SwiftUI

转载 作者:行者123 更新时间:2023-12-01 21:46:01 25 4
gpt4 key购买 nike

我有这个使用“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

}
}
}

当我单击 TextView 时,它不会向控制台打印任何内容,有时还会崩溃。我该如何解决这个问题?

最佳答案

必须提供有效的 URL,例如

 let attributedString = NSMutableAttributedString(string: myText)
attributedString.apply(link: "https://www.google.com", subString: myText)

关于ios - UITextView 与 NSMutableAttributedString 与链接 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62219038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com