SwiftUI position text bottom right?
Asked Answered
W

2

15

Is there a better way of positioning text in SwiftUI, in the example below I am positioning the text in the bottom right corner of a ZStack, it works fine but seems long winded, am I missing a simpler way ... The orange lines are just for debugging, so that the spacers are visible in the view.

CODE

struct DisplayTwoView: View {
    var body: some View {
        ZStack {
            Rectangle().foregroundColor(.blue)
            Group {
                VStack {
                    Spacer().frame(width: 5).background(Color.orange)
                    HStack {
                        Spacer().frame(height: 5).background(Color.orange)
                        Text("RABBITS").fontWeight(.black)
                    }
                }
            }.padding()
        }
    }
}

VIEW

enter image description here

Wideangle answered 2/4, 2020 at 12:22 Comment(0)
B
26

Try this one (tested with Xcode 11.4 / iOS 13.4)

struct DisplayTwoView: View {
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            Rectangle().foregroundColor(.blue)
            Text("RABBITS").fontWeight(.black)
                .padding()
        }
    }
}
Boon answered 2/4, 2020 at 12:32 Comment(4)
Thats a good option, yup I had overlooked the fact that you could align the stack.Wideangle
Is there a way to align only a single object inside the contents of the ZStack?Stucker
Have same question like @StuckerRolan
Checkout alignmentGuides, hackingwithswift.com/books/ios-swiftui/…. Been a bit of time, but pretty sure they worked for me.Stucker
M
5

Another way is via the .frame modifier, like this:

ZStack {
    Text("RABBITS")
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}
Meany answered 5/7, 2022 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.