【发布时间】:2020-07-14 21:55:51
【问题描述】:
我需要将我的 MultilineTextField 视图(包装的 UITextView)分配给变量 textField,以便以后能够从 ContentView 中的按钮调用其方法 updateTextStyle(该方法获取选定的文本并转动它变成粗体)。问题是 MultilineTextField 依赖于@State var range,因此无法编译。有什么可能的解决方法?
struct ContentView: View {
@State private var range: NSRange?
@State var textField = MultilineTextField(rangeSelected: $range)
var body: some View {
VStack {
textField
Button(action: {
self.textField.updateTextStyle()
}) {
Text("Update text style")
}
}
}
}
如果相关,MultilineTextField(我试图删除不必要的 - 希望很清楚)
struct MultilineTextField: UIViewRepresentable {
let textView = UITextView()
@Binding var rangeSelected: NSRange?
@State var attributedNoteText = NSMutableAttributedString(string: "Lorem ipsum")
func makeUIView(context: Context) -> UITextView {
// ...
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.attributedText = attributedNoteText
}
func updateTextStyle() {
if self.rangeSelected != nil {
// apply attributes (makes the selected text bold)
} else {
print("rangeSelected is nil")
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self, $attributedNoteText)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: MultilineTextField
var text: Binding<NSMutableAttributedString>
init(parent: MultilineTextField, _ text: Binding<NSMutableAttributedString>) {
self.parent = parent
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
let attributedStringCopy = textView.attributedText?.mutableCopy() as! NSMutableAttributedString
parent.textView.attributedText = attributedStringCopy
self.text.wrappedValue = attributedStringCopy
}
func textViewDidChangeSelection(_ textView: UITextView) {
parent.rangeSelected = textView.selectedRange // not sure about this one
}
}
}
(我知道这里可能存在一些额外的错误 - 这是我第一次在 SwiftUI 中使用 UIKit。感谢您的帮助)
【问题讨论】:
-
您是否介意发帖
MultilineTextField以获得进一步的帮助