Home > Software engineering >  How do we control the automatic dividers in SwiftUI forms?
How do we control the automatic dividers in SwiftUI forms?

Time:12-19

I'm curious, is there a way we can control (or make sense of) the automatic dividers that swiftui puts between items?

Here's some code showing strange behaviour (on iOS simulator):

struct FormSeparator: View {
    @State private var passwd = ""
    var body: some View {
        Form {
            ZStack(alignment: .trailing) {
                TextField("password", text:$passwd)
                Text("8 chars min")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            TextField("confirm", text:$passwd)
        }
    }
}

Here's the result:

example of strange divider

This seems to have something to do with the Text that I'm stacking on top of the password field. If I change it the Text to Image(systemName: "lock") then everything works as you'd expect:

example of normal divider

Mind you, I don't even understand why it doesn't extend all the way across the form in that case. Presumably this is deliberate, has anyone seen anything official about this situation? Do we know how to control this?

CodePudding user response:

In iOS 16, List/Form row separator insets automatically and aligns with the text. In iOS 16, we got two new alignments, listRowSeparatorLeading and listRowSeparatorTrailing, to work with alignmentGuide(_:computeValue:).

ZStack(alignment: .trailing) {
    TextField("password", text:$passwd)
    Text("8 chars min")
        .font(.caption)
        .foregroundColor(.secondary)
}
.alignmentGuide(.listRowSeparatorLeading) { viewDimensions in
    return 0
}
  • Related