Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Text spills outside of boundary of Rectangle in SwiftUI with overlay

I want Text 1 and Text 2 in the blue rectangle to be within the boundaries of the Rectangle but when using overlay it seems to spill outside of the given boundary. How can one fix this?

I tried ZStack as well but had the same result.

import SwiftUI

struct ContentView: View {

    var body: some View {
        VStack {
            ZStack {
                Rectangle()
                    .stroke(lineWidth: 1)
                    .frame(width: 1, height: 55)
                Rectangle()
                    .stroke(lineWidth: 10)
                    .cornerRadius(15)
                    .foregroundColor(Color.blue)
                    .frame(width: .infinity, height: 60)
                    .padding()
            }
            .overlay(
                HStack {
                    Text("Text 1")
                    Spacer()
                    Text("Text 2")
                }
            )
        }
    }
}

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to place overlay in different place (order of modifiers is important!), like

var body: some View {
    VStack {
        ZStack {
            Rectangle()
                .stroke(lineWidth: 1)
                .frame(width: 1, height: 55)
            Rectangle()
                .stroke(lineWidth: 10)
                .cornerRadius(15)
                .foregroundColor(Color.blue)
                .overlay(                     
                    HStack {                 // << here !!
                        Text("Text 1")
                        Spacer()
                        Text("Text 2")
                    }
                    .padding(.horizontal)
                )
                .frame(width: .infinity, height: 60)
                .padding()
        }
    }
}

demo

Tested with Xcode 13 / iOS 15

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading