Home > Enterprise >  How to get information about width and height of View inside of .background() modifier in SwiftUI
How to get information about width and height of View inside of .background() modifier in SwiftUI

Time:08-04

I want to create a button like this:

SwiftUI Button with stroke

Here is the code for that:

                Button {
                    
                } label: {
                    VStack {
                        Image(systemName: "plus")
                            .foregroundColor(Color("SecondaryTextColor"))
                            .font(.title2)
                    }
                    .frame(maxWidth: .infinity, maxHeight: UIScreen.main.bounds.height * 0.1)
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .strokeBorder(Color("MainBackgroundColor"), style: StrokeStyle(lineWidth: 3, dash: [8]))
                            .frame(width: 345, height: 70)
                    )
                    .background(Color("SecondaryBackgroundColor"))
                    .cornerRadius(20)
                }

Right now you can see that background RounderRectangle has fixed width and height. I would like to calculate the values for the stroke to be dynamic and always a little bit less than the Vstack. How can I achieve it?

CodePudding user response:

You just need padding (it gives constant internal inset independently of external size, ie. internal stroke will always fit in filled area):

.frame(maxWidth: .infinity, maxHeight: UIScreen.main.bounds.height * 0.1)
.background(
    RoundedRectangle(cornerRadius: 20)
        .strokeBorder(Color("MainBackgroundColor"), style: StrokeStyle(lineWidth: 3, dash: [8]))
        .padding(4)  // << here !! (set value per needs)
)

enter image description here

Tested with Xcode 13.4 / iOS 15.5

  • Related