Stanley Fuller
Stanley Fuller

Reputation: 138

SwiftUI - Expand TextField to Fill View

I am trying to create a TextField that spans across the entire window. Currently it only expands to fill the view on the horizontal axis. I'm aiming to achieve something similar to that seen in TextEdit.

Here is my code so far:

struct ContentView: View {
    @State var contents: String = "Hello World\nThis is a test.";

    var body: some View {
        VStack() {
            TextField("Notes", text: $contents)
                .lineLimit(nil)
        }
        .frame(height: 600)
    }
}

Application Screenshot

Is this possible in SwiftUI or will I need to revert to using legacy AppKit components?

Upvotes: 3

Views: 3003

Answers (3)

Waxhaw
Waxhaw

Reputation: 829

Just replying to this as nobody's given a decent answer yet besides wrapping UIKit.

TextEditor(text: $contents)

Is the better path as it WILL behave like you wish as compared to TextField(). It automatically takes care of scrolling and expanding to the View area allowed.

TextEditor WILL require you to be on at least iOS 14. If you're not on iOS 14 then wrapping the UIKit control is your best option.

Upvotes: 2

Hrabovskyi Oleksandr
Hrabovskyi Oleksandr

Reputation: 3265

It seems, that there is bug with TextField line limit, according to this answer and comments to it.

I believe in this thread you can find answer, how achieve what you want.

Upvotes: 0

Dragos
Dragos

Reputation: 1040

I've found that wrapping an NSTextView is still be the best way to achieve something similar to that seen in TextEdit. So yes, at least now you will have to use legacy AppKit components in your SwiftUI code.

struct MultilineTextView: NSViewRepresentable {
    typealias NSViewType = NSTextView

    @Binding var text: String

    func makeNSView(context: Self.Context) -> Self.NSViewType{
        let view = NSTextView()
        view.isEditable = true
        view.isRulerVisible = true
        return view
    }

    func updateNSView(_ nsView: Self.NSViewType, context: Self.Context) {
        nsView.string = text
    }
}


struct ContentView: View {
    @State var contents: String = "Hello World\nThis is a test.";

    var body: some View {
        VStack() {
            MultilineTextView(text: $contents)
        }.background(Color.white)
    }
}

Upvotes: 1

Related Questions