如何获取默认系统内边距值?

15

我正在使用SwiftUI,但我创建了一个可表示的UITextView

我想将插图设置为系统默认填充,使其与应用程序的其余部分匹配。

这是我现在正在使用的:

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

这看起来还不错,但我真的更喜欢使用默认的系统填充,如果可能的话。

padding() 的文档如下:

长度

此视图在每个边缘上的插入量。 如果为nil,则该量为系统默认量。

我如何获取默认的系统填充 CGFloat 值?


我认为在SwiftUI中,padding相当于LayoutMargin:https://developer.apple.com/documentation/uikit/uiview/1622566-layoutmargins - Andrea Miotto
2个回答

3

因此,我创建了一个宽度/高度为0且顶部具有默认填充的矩形,然后读取该矩形的高度(即默认填充的大小),并将其存储在绑定的CGFloat中。它也会隐藏自身。

然后,您可以将该值传递给您的UITextView包装器。

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)
    }
}

0

我不知道你的确切用例,但一个可能的解决方法是使用容器栈(例如VStackGeometryReader)。然后将可用宽度传递给UIViewRepresentable并将其设置为其preferredMaxLayoutWidth

VStack(alignment: .leading) {
                GeometryReader { geometry in
                    UIKitLabel(width: geometry.size.width,
                      attributedString: NSAttributedString(string: "Hello"))
                        .fixedSize()
                        .layoutPriority(0)
                }
            }.padding()

然后在自定义组件的makeUIView方法内执行以下操作:

func makeUIView(context: Context) -> UILabel {
     let label = UILabel(frame:CGRect.zero)
     label.preferredMaxLayoutWidth = width
     return label
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接