Home > Mobile >  SwiftUI - Text elements not starting from same leading position
SwiftUI - Text elements not starting from same leading position

Time:01-20

I am still a beginner in swiftUI.

Adding code and screenshot which will have explain my problem better. In the below screenshot, how can I align 'E' of first line with 'T' of 2nd line. I want both 'Text' elements to have same leading space i.e. both should start from the same position from left.

I have seen cases where people are using just one Text element and '\n' to move text to the next line and that aligns the text, but in my case I will be having more elements such as TextField and some more Text elements below these 2 texts hence I can't use the '\n' idea.

Code:

struct TestData: View {
    var body: some View {
        ZStack {
            Image("backgroundImage").resizable().edgesIgnoringSafeArea(.all).scaledToFill()
            VStack(alignment: .leading, spacing: 10) {
                Text("Enter your Data")
                    .font(.largeTitle).bold()
                    .frame(width: UIScreen.main.bounds.width-50, height: 33.0)
                
                Text("This is a very very long text to wrap on the next line. This text is of 2 lines.")
                    .font(.callout)
                    .frame(width: UIScreen.main.bounds.width-50, height: 80.0)
                    .foregroundColor(.gray)
                    .lineLimit(nil)
                
                HStack {
                    // Contains image and textfield. Data will be entered in textfield.
                }

                // Move Text and Button elements.
            }.offset(x: -10, y: -100)
        }
    }
}

struct TestData_Previews: PreviewProvider {
    static var previews: some View {
        TestData()
    }
}

Screenshot:

enter image description here

CodePudding user response:

In general, don't set fixed frames; SwiftUI tends to work better when you let the layout engine do its thing. Using maxWidth/maxHeight and minWidth/minHeight can be useful for giving clues to the layout engine about what you want.

Similarly with offset - This moves things around but doesn't change their layout bounding box, so you can end up with overlapping elements (which is fine if that is what you want).

For your layout, you can simply remove the frame and offset and use some padding to shift everything in from the leading edge:

VStack(alignment: .leading, spacing: 10) {
    Text("Enter your Data").font(.largeTitle)
    .bold()
                
    Text("This is a very very long text to wrap on the next line. This text is of 2 lines.").font(.callout)
    .foregroundColor(.gray)
    .lineLimit(nil)
                
    HStack {
           // Contains image and textfield. Data will be entered in textfield.
           }
}.padding(.leading,50)
  • Related