使用 SwiftUI 的 relativeWidth 仅适用于框架视图 [英] Using SwiftUI's relativeWidth only works inside frame view

查看:16
本文介绍了使用 SwiftUI 的 relativeWidth 仅适用于框架视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to build a bar graph element in SwiftUI whose width is proportional to its parent view based on the value of the element. Here's a boiled down version of the problem:

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

...产生:

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

I expected the relativeWidth modifier to use its parent which should be the width of the screen, so the color view should be half the width of the screen and centered. If the view is embedded in a frame view, it works as expected:

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

我需要视图在其容器内灵活而无需指定框架.我意识到有 GeometryReader,但是当相对宽度似乎正是这里所需要的时,这似乎有点麻烦.有什么想法吗?

I need the view to be flexible inside its container without specifying a frame. I realize there's the GeometryReader, but this seems like a bit of a hack when relativeWidth seems to be exactly what's needed here. Any ideas?

推荐答案

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

Well, .relativeWidth() is gone with beta4... so I am updating my answer.

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

As an alternative to GeometryReader, that comes with its own inconveniences, in your case using a Shape may be a good alternative.

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

The path() function where you define your shape, has a rect parameter that helps you with your drawing. Here's a solution:

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

这篇关于使用 SwiftUI 的 relativeWidth 仅适用于框架视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆