这个问题让我有些困惑,所以我希望得到一些帮助。我有一个使用UITextView的SwiftUI应用程序,但是当我将内容放入其中时,文本不会自动换行。我正在同时显示和编辑文本的SwiftUI视图,但目前都无法使用。
第二个框中的文本更长,但高度不变。
func makeUIView(context: Context) -> UITextView {
view.isScrollEnabled = false
view.isEditable = editable
view.isUserInteractionEnabled = true
view.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
view.text = self.text
// For debugging
view.layer.borderColor = UIColor.black.cgColor
view.layer.borderWidth = 1.0
var fontPref = UIFont.preferredFont(forTextStyle: render.font)
if render.bold && render.italic {
fontPref = fontPref.bolditalic()
} else if render.bold {
fontPref = fontPref.bold()
} else if render.italic {
fontPref = fontPref.italic()
}
view.font = fontPref
view.textColor = render.color
view.textAlignment = render.align
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
view.textContainer.lineBreakMode = .byWordWrapping
view.delegate = context.coordinator
return view
}
我尝试了一些解决方案,但是没有一个适合我的用例。
谢谢!
答案 0 :(得分:0)
这是一个有效的自定义文本视图,用于包装文本并调整高度:
import SwiftUI
struct NoteTextView: UIViewRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
@Binding var text: String
var onEndEditing: () -> Void
typealias UIViewType = UITextView
var configuration = { (view: UIViewType) in }
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType {
let textField = UIViewType()
textField.delegate = context.coordinator
textField.font = UIFont.preferredFont(forTextStyle: .body)
textField.text = text
textField.isScrollEnabled = true
textField.isEditable = true
textField.isUserInteractionEnabled = true
return textField
}
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) {
uiView.text = text
configuration(uiView)
}
class Coordinator : NSObject, UITextViewDelegate {
var parent: NoteTextView
init(_ uiTextView: NoteTextView) {
self.parent = uiTextView
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return true
}
func textViewDidChange(_ textView: UITextView) {
self.parent.text = textView.text
}
}
}