首页 > 解决方案 > 具有 swiftui 形状的自适应框架(小部件)大小

问题描述

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

struct WidgetView: View {
    var body: some View {

        ZStack {

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

            Text("TestingText")

        }
    }
}

标签: iosswiftuisizeframeshapes

解决方案


我想你想要这个

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

输出

演示


推荐阅读