具有 swiftui 形状的自适应框架(小部件)大小

Adaptive frame (widget) size with swiftui shape

我想调整小部件的大小以适应小部件内容的整体大小。问题是,标准形状(小部件的背景)默认为可用 space,我不想硬编码它的框架。任何建议,例如使用 GeometryReader?

struct WidgetView: View {
    var body: some View {

        ZStack {

            RoundedRectangle(cornerRadius: 40, style: .continuous)
                .foregroundColor(.gray)

            Text("TestingText")

        }
    }
}

我猜你想要这个

struct WidgetView: View {
    var body: some View {

        Text("TestingText")
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray))
    }
}

更新:我认为您的担心是由于圆角半径较大,可能会削减一些内部内容。

这里有一些方法

struct WidgetView<V: View>: View {   // more generic view
    var content: () -> V
    var body: some View {
        content()
           .background(RoundedRectangle(cornerRadius: 40, style: .continuous)
            .foregroundColor(.gray).padding(-20))  // compensation !!
    }
}

测试(Xcode 11.4 / iOS 13.4)

WidgetView {
    VStack {
        Image(systemName: "car")
            .resizable().frame(width: 80, height: 80)
        Text("Some Label")
    }
}

输出