使用 SwiftUI 的 relativeWidth 仅在框架视图内有效

Using SwiftUI's relativeWidth only works inside frame view

尝试在 SwiftUI 中构建一个条形图元素,其宽度根据元素的值与其父视图成比例。这是问题的简化版本:

struct BarView : View {
var body: some View {
    Color.purple
        .relativeWidth(0.5)
    }
}

...产生:

我希望 relativeWidth 修饰符使用它的父项,它应该是屏幕的宽度,所以彩色视图应该是屏幕宽度的一半并居中。如果视图嵌入在框架视图中,它会按预期工作:

struct BarView : View {
    var body: some View {
        Color.purple
            .relativeWidth(0.5)
            .frame(width: 200, height: 200)
    }
}

我需要视图在其容器内灵活而不指定框架。我知道有 GeometryReader,但是当 relativeWidth 似乎正是这里所需要的时,这似乎有点麻烦。有什么想法吗?

好吧,.relativeWidth() beta4 已经消失了...所以我正在更新我的答案。

作为 GeometryReader 的替代方案,它有其自身的不便之处,在您的情况下,使用 Shape 可能是一个不错的替代方案。

用于定义形状的 path() 函数有一个 rect 参数,可帮助您进行绘图。这是一个解决方案:

import SwiftUI

struct BarShape: Shape {
    let percent: CGFloat

    func path(in rect: CGRect) -> Path {

        let fillPart = CGRect(x: 0, y: 0, width: rect.size.width * percent, height: rect.size.height)

        var p = Path()

        p.addRoundedRect(in: fillPart, cornerSize: CGSize(width: 8, height: 8))

        return p
    }
}

struct ContentView: View {
    var body: some View {
        BarShape(percent: 0.7).fill(Color.purple)
    }
}