NavbarView() {
TextField("Search", text: $searchText).padding()
Spacer()
Picker(selection: $sharedState.typeTreeViewRole, label: Text("View")) {
Text("Business").tag(TypeTreeViewRole.business)
Text("Expert").tag(TypeTreeViewRole.expert)
}
.frame(width: 150) // Set a fixed width for the Picker
.padding()
.pickerStyle(SegmentedPickerStyle())
Spacer()
Button(action: {}) {
Text("Create Type tree")
}
}
look like this:
Picker is not centerered, but it is on the right. Why? How to fix?
>Solution :
The search field is taking up all of the available space, and your spacers are at their minimum sizes. Even if the search field wasn’t doing that, it probably wouldn’t be centered – you’re not telling the layout engine that’s what you want.
These layout things in SwiftUI can be frustrating and there are lots of ways to solve them. One option is that instead of spacers, set frames with maximum width and alignments for each component:
NavbarView() {
TextField("Search", text: $searchText).padding()
.frame(maxWidth: .infinity, alignment: .leading)
Picker(selection: $sharedState.typeTreeViewRole, label: Text("View")) {
Text("Business").tag(TypeTreeViewRole.business)
Text("Expert").tag(TypeTreeViewRole.expert)
}
.frame(maxWidth: .infinity)
.pickerStyle(SegmentedPickerStyle())
Button(action: {}) {
Text("Create Type tree")
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
Given no additional information, the layout engine will make each view take up an equal amount of space, and the alignment parameter puts the content in the appropriate space for each block.
