SwiftUI UIViewRepresentable - UITextView 检测属性文本的更改

问题描述 投票:0回答:1

我无法让文本视图检测

@Binding
属性中的更改,因为它具有属性文本而不是文本。我如何检测这些变化并进行相应更新。我尝试使 UITextView 本身成为一种状态,但这不起作用。这是我的代码:

struct MultilineTextView: UIViewRepresentable {
    @Binding var text: NSMutableAttributedString
    @State private var view = UITextView()

    func makeUIView(context: Context) -> UITextView {
        self.view.isScrollEnabled = true
        self.view.isEditable = true
        self.view.isUserInteractionEnabled = true
        self.view.autocorrectionType = .no
        self.view.inputAssistantItem.leadingBarButtonGroups.removeAll()
        return self.view
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        print("Update")
        let all = NSMakeRange(0, text.length)
        text.addAttribute(.font, value: UIFont(name: "Courier", size: 20.0)!, range: all)
//        text.addAttribute(.foregroundColor, value: UIColor.white as! Any, range: all)
//        text.addAttribute(.backgroundColor, value: UIColor.black as! Any, range: all)

        let regex = try! NSRegularExpression(pattern: "hi^", options: [])
        let matches = (regex.matches(in: text.string, options: [], range: all))

        for match in matches {
            print(match.range)

            text.addAttribute(.foregroundColor, value: UIColor.blue, range: match.range(at: 1))
        }

        uiView.attributedText = text
    }
}

swift uikit swiftui nsattributedstring nsmutableattributedstring
1个回答
0
投票

您应该在 UIViewRepresentable 中使用 Coordinator 类。 你不需要 prop @State private var view = UITextView()。 您创建 uikit 视图,您希望 swiftui 在 makeUIView 方法中显示该视图。 比更新你想要的任何绑定道具(在 uitextview 中它可能是文本或 attibutedtext) 您创建协调器并符合 uitextviewdelegate 协议并将其附加到 makeUIView 中的视图(view.delegate = context.coordinator),并且您可以访问 textViewDidChange 委托方法来管理绑定值:

struct MultilineTextView: UIViewRepresentable {
@Binding var text: NSAttributedString

func makeUIView(context: Context) -> UITextView {
    let view = UITextView()
    view.isScrollEnabled = true
    view.isEditable = true
    view.isUserInteractionEnabled = true
    view.autocorrectionType = .no
    view.inputAssistantItem.leadingBarButtonGroups.removeAll()
    view.delegate = context.coordinator
    return view
}

func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.attributedText = text
}

func makeCoordinator() -> Coordinator {
    Coordinator(self)
}

class Coordinator: NSObject, UITextViewDelegate {
    var parent: MultilineTextView

    init(_ parent: MultilineTextView) {
        self.parent = parent
    }

    func textViewDidChange(_ textView: UITextView) {
        parent.text = textView.attributedText
    }
}

}

对我的英语感到抱歉

© www.soinside.com 2019 - 2024. All rights reserved.