如何在 SwiftUi 中创建多行 TextField?喜欢笔记应用程序? [英] How to create a multiline TextField in SwiftUi ? like the notes app?
本文介绍了如何在 SwiftUi 中创建多行 TextField?喜欢笔记应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个多行文本字段,它会自动添加换行符并带有滚动视图,就像笔记应用程序一样,我们在 SwiftUI 中有什么直接的方法可以做到这一点吗?
I want to create a multiline textfield that automatically ads line breaks and with scroll view, just like the notes app, is there any direct way we can do this in SwiftUI ?
推荐答案
这适用于 Xcode Version 11.0 beta 6:
This works in Xcode Version 11.0 beta 6:
import SwiftUI
struct ContentView: View {
@State var text = ""
var body: some View {
VStack {
Text("text is: \(text)")
TextView(
text: $text
)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
}
struct TextView: UIViewRepresentable {
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UITextView {
let myTextView = UITextView()
myTextView.delegate = context.coordinator
myTextView.font = UIFont(name: "HelveticaNeue", size: 15)
myTextView.isScrollEnabled = true
myTextView.isEditable = true
myTextView.isUserInteractionEnabled = true
myTextView.backgroundColor = UIColor(white: 0.0, alpha: 0.05)
return myTextView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
class Coordinator : NSObject, UITextViewDelegate {
var parent: TextView
init(_ uiTextView: TextView) {
self.parent = uiTextView
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return true
}
func textViewDidChange(_ textView: UITextView) {
print("text now: \(String(describing: textView.text!))")
self.parent.text = textView.text
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
这篇关于如何在 SwiftUi 中创建多行 TextField?喜欢笔记应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文