Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 965
fuzzygoat Avatar asked Apr 02 '20 12:04

fuzzygoat


People also ask

How to position text in SwiftUI?

To align a text view along the horizontal axis, you need to use . frame() modifier with maxWidth set to . infinity and alignment to the alignment you want.

How to center align text in SwiftUI?

When SwiftUI's Text views wrap across multiple lines, they align to their leading edge by default. If you want to change that, use the multilineTextAlignment() modifier to specify an alternative, such as . center , or . trailing .

What is a Hstack?

A view that arranges its subviews in a horizontal line.


1 Answers

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()
        }
    }
}
like image 180
Asperi Avatar answered Oct 17 '22 10:10

Asperi