如何在SwiftUi中创建多行TextFeild?喜欢记事应用?

时间:2019-08-27 17:55:39

标签: swiftui

我想创建一个多行文本字段,该文本行可以自动广告换行符,并具有滚动视图,就像Notes应用程序一样,在SwiftUI中有什么直接方法可以做到这一点?

3 个答案:

答案 0 :(得分:4)

这适用于Xcode 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()
    }
}

答案 1 :(得分:1)

您要找的实际上是29。 SwiftUI中没有当前等效项,因此您必须使用myline[29:]结构来实现此目的。有关如何包装UIKit视图和视图控制器以用于SwiftUI的信息,请参见Apple's SwiftUI + UIKit tutorial;有关可能的实现方式(以及易于忽略的细节的解决方案),请参见this question

答案 2 :(得分:0)

你可以使用

TextEditor(text: $text)