13

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

Zorayr
  • 23,770
  • 8
  • 136
  • 129
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

2 Answers2

21

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()
        }
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
3

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

ZStack {
    Text("RABBITS")
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}
Xtian D.
  • 434
  • 5
  • 5