【问题标题】:SwiftUI view with different widths with fill depending on the percentage不同宽度的 SwiftUI 视图,根据百分比填充
【发布时间】:2021-10-15 17:10:51
【问题描述】:

创建视图的最佳方法是什么(如下图所示)?这样它的宽度就是文本内容和填充的大小,考虑到百分比。我通过 Frame 和 GeometryReader 尝试了几个选项,但结果要么是固定宽度的视图,要么是屏幕宽度的视图。

也许有更优雅的方式。

【问题讨论】:

    标签: ios swift view swiftui


    【解决方案1】:
    var percent: CGFloat = 0.7
    
    var body: some View {
        VStack(alignment: .leading) {
            cell("Lorem")
            cell("Lorem ipsum")
            cell("Lorem ipsum dolor")
            cell("Lorem ipsum dolor sit")
            cell("Lorem ipsum dolor sit amet")
        }
    }
    
    @ViewBuilder
    func cell(_ string: String) -> some View {
        Text(string)
            .padding(.all, 5)
            .background(
                GeometryReader { geometry in
                    ZStack(alignment: .leading) {
                        Rectangle()
                            .foregroundColor(.green)
                            .frame(width: geometry.size.width * percent, height: geometry.size.height)
                        Capsule()
                            .stroke(Color.black, lineWidth: 1)
                    }
                }
            )
            .clipShape(Capsule())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多