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

时间:2019-07-03 18:59:13

标签: swiftui

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

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

...产生:

enter image description here

我希望relativeWidth修饰符使用其父元素,该父元素应为屏幕的宽度,因此颜色视图应为屏幕宽度的一半并居中。如果该视图嵌入在框架视图中,则它将按预期工作:

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

In frame

我需要在其容器内保持灵活的视图,而无需指定框架。我意识到这里有GeometryReader,但是当relativeWidth似乎正是这里需要的东西时,这似乎有点不合时宜。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好吧,.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)
    }
}