【问题标题】:Using SwiftUI's relativeWidth only works inside frame view使用 SwiftUI 的 relativeWidth 仅适用于框架视图
【发布时间】:2019-07-03 18:59:13
【问题描述】:

尝试在 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 似乎正是这里所需要的时,这似乎有点像黑客。有什么想法吗?

【问题讨论】:

  • 这是一个测试版产品,谁知道呢,也许它的行为正是它的预期行为。

标签: swiftui


【解决方案1】:

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

【讨论】:

  • 想了很多,但似乎我不了解系统。仍在掌握新概念。欣赏它。
猜你喜欢
  • 2010-10-22
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-08-29
  • 2020-11-21
相关资源
最近更新 更多