UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

ForEach: how to force row height?

Forums > SwiftUI

I display some data using ForEach. I want one row to have a TextField as the first item rather than the Text on every other row. So I have code like this (obviously, simplified):

struct Test: View {
    @State var s: String = ""

    var body: some View {
        VStack {
            ForEach (0..<5) { n in
                HStack {
                    Spacer()
                    if n==3 {
                        TextField("", text: $s).frame(width: 25)
                            .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(UIColor.systemBlue), lineWidth: 1))
                    } else {
                        Text(String(n)).frame(width: 25)
                    }
                    Text("rest of row")
                    Spacer()
                }
                .background(Color(n%2==0 ? UIColor.systemBackground: UIColor.secondarySystemFill))
            }
        }
    }
}

It works, but the row containing the TextField ends up with additional space above and below it, which doesn't look nice. Is there a way to prevent this from happening? I've tried adding .frame(height: 20) modifiers in various places but it doesn't make any difference.

Thanks in advance, as usual.

Jeremy

2      

Nobody? There must be a way to prevent ForEach inserting extra spacing above and below a row containing a TextEntry field, surely?

2      

It's dependent on the size of the font inside the TextField as well as what TextFieldStyle is applied. You can always add negative vertical padding, but I'm not sure it will look very good.

2      

The curious thing is that the spacing is outside the overlay rectangle and outside the background colour of the HStack.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.