0

I'm working on a SwiftUI app that needs a TextField that dynamically expands as the user types but with a maximum number of lines. I want it to:

Start with a single line Grow as the user types until reaching max lines Then become scrollable once max lines is reached

Here's my current implementation, but it doesn't handle the height correctly:

struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
        VStack {
            TextField("Enter your text here", text: $text)
                .padding()
                .frame(minHeight: 40)
                .background(Color.gray.opacity(0.2))
                .cornerRadius(8)
                .lineLimit(5)
        }
        .padding()
    }
}

The TextField doesn't grow properly, and once the text exceeds the visible area, it just clips instead of becoming scrollable. How can I implement this correctly in SwiftUI?

1

1 Answer 1

1

You just need the .axis: .vertical parameter:

import SwiftUI

struct ExpandingTextField: View {
    
    @State private var text = ""
    
    var body: some View {
        TextField("Enter your text here", text: $text, axis: .vertical)
            .padding(10)
            .background(Color.gray.opacity(0.2), in: .rect(cornerRadius: 8))
            .lineLimit(5)
            .padding()
    }
}

#Preview {
    ExpandingTextField()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.