Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get default system padding value?

Tags:

ios

swift

swiftui

I'm using SwiftUI but I've created a representable UITextView.

I want to set the insets to the system default padding so it matches the rest of the app.

Here is what I'm using right now:

UITextView().textContainerInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)

This looks decent but I would really prefer to utilize the default system padding, if possible.

The documentation for padding() states the following:

length

The amount to inset this view on each edge. If nil, the amount is the system default amount.

How do I obtain the default system padding CGFloat value?

like image 948
stardust4891 Avatar asked Nov 14 '19 12:11

stardust4891


People also ask

What is the default value of padding?

Padding values are set using lengths or percentages, and cannot accept negative values. The initial, or default, value for all padding properties is 0 .

What's the default padding () in SwiftUI?

If you set the value to nil , SwiftUI uses a platform-specific default amount. The default value of this parameter is nil .

What is padding () in Swift?

By utilizing .padding() on a UI element, Swift UI will place a system calculated amount of padding around the entire object. If you want to place padding on a specific side of an object, lets say the top of the object, you can do so using the following example: struct SomeView: View { var body: some view { VStack {

What is padding in IOS?

The object for defining space around the content in a table cell.


1 Answers

So, I made a rectangle with width/height as 0 and the default padding on top, then I read the height of the rectangle (which is the size of the default padding) and store it in a bound CGFloat. It also hides itself.

You could then pass that value into your UITextView wrapper.

struct Defaults: View {
    @Binding var padding: CGFloat
    @State var isHidden = false
    @ViewBuilder
    var body: some View {
        if !isHidden {
            Rectangle()
                .frame(width: 0, height: 0)
                .padding(.top)
                .background(GeometryReader { geometry in
                    Rectangle().onAppear {
                        self.padding = geometry.size.height
                        self.isHidden = true
                    }
                })
        }
    }
}


struct Example: View {
    @State var padding = CGFloat()
    @ViewBuilder
    var body: some View {
        Defaults(padding: $padding)
        Rectangle().frame(width: padding, height: padding)
    }
}
like image 80
Tomatrow Avatar answered Oct 15 '22 07:10

Tomatrow