So I am trying to align a HStack
in the center of the screen and have bell icon aligned on the right side of the screen.
Below is the code I have:
var body: some View {
ZStack {
Spacer()
if(self.top == 0) {
UserFeedView()
} else {
MapView()
}
VStack() {
Spacer().frame(maxHeight: 80)
HStack() {
HStack(spacing: 20) {
Button(action: {
self.top = 0
}) {
Text("Feed").foregroundColor(self.top == 0 ? .black : Color.black.opacity(0.45))
.fontWeight(self.top == 0 ? .bold : .none)
.padding(.vertical )
}
Text("|")
.font(.system(size:20))
.foregroundColor(Color.black.opacity(0.3))
Button(action: {
self.top = 1
}) {
Text("Map").foregroundColor(self.top == 1 ? .black : Color.black.opacity(0.45))
.fontWeight(self.top == 1 ? .bold : .none)
.padding(.vertical )
}
}
.padding(.horizontal, 23)
.background(.ultraThinMaterial, in : RoundedRectangle(cornerRadius: 16.0))
Image(systemName: "bell")
.frame(alignment: .trailing)
.listRowInsets(EdgeInsets())
}
Spacer()
}
.ignoresSafeArea()
}
}
and the result:
As you can see, the selector
between feed and map is not centered in the middle of the screen and the bell icon is not properly aligned on the right side. If I remove the bell icon, the Hstack selector
is perfectly centered
2
Answers
I would be tempted to structure the code something like this:
I would suggest the easiest way is to have your
HStack
use the full available width and then set the bell image on the right using an overlay:If you know the size of the bell image (including padding) then you could also do it by using padding on the left to balance the width of the image on the right. That way you can keep the selector centered. But I would suggest, an overlay is simpler.
BTW, just in case you didn’t know, you can set
.pickerStyle(.segmented)
on a nativePicker
to get a similar kind of selector, instead of rolling your own.