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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.