我有一个SwiftUI Texteditor,每当我按下更新按钮时,颜色应该应用于文本,但它只是重置为initialValue。有人能帮助我吗?
import SwiftUI
class TextColorUpdater: ObservableObject {
@Published var attributedText: NSAttributedString
init(initialText: String) {
self.attributedText = TextColorUpdater.highlightText(initialText)
}
func update() {
print(attributedText.string)
self.attributedText = TextColorUpdater.highlightText(attributedText.string)
}
static func highlightText(_ text: String) -> NSAttributedString {
let mutableAttributedString = NSMutableAttributedString(string: text)
if let regex = try? NSRegularExpression(pattern: "\\bred\\b", options: .caseInsensitive) {
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
let nsRange = match.range
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: nsRange)
}
}
return mutableAttributedString
}
}
struct HighlightedTextEditor: UIViewRepresentable {
@Binding var attributedText: NSAttributedString
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isEditable = true
textView.isSelectable = true
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.attributedText = attributedText
}
}
struct ContentView: View {
@StateObject var textColorUpdater = TextColorUpdater(initialText: "This is a redd red red red car. The sky is not red")
var body: some View {
VStack {
HighlightedTextEditor(attributedText: $textColorUpdater.attributedText)
Button("Update") {
textColorUpdater.update()
}
}
}
}
字符串
1条答案
按热度按时间von4xj4u1#
当
UITextView
的文本发生变化时,你永远不会更新@Binding
!绑定不会知道它与UITextView
的文本相关并自行更新!您需要检测
UITextView
的文本更改。您可以使用UITextViewDelegate
来完成。为了符合此要求,您需要Coordinator
。字符串