fuzzygoat
fuzzygoat

Reputation: 26223

SwiftUI position text bottom right?

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

Upvotes: 15

Views: 13219

Answers (2)

Asperi
Asperi

Reputation: 258501

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()
        }
    }
}

Upvotes: 26

Xtian D.
Xtian D.

Reputation: 483

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

ZStack {
    Text("RABBITS")
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}

Upvotes: 5

Related Questions