尝试在 SwiftUI 中构建一个条形图元素,其宽度根据元素的值与其父 View 成比例。这是问题的简化版本:
struct BarView : View {
var body: some View {
Color.purple
.relativeWidth(0.5)
}
}
...产生:
我希望 relativeWidth 修饰符使用它的父元素,它应该是屏幕的宽度,所以彩色 View 应该是屏幕宽度的一半并居中。如果 View 嵌入在框架 View 中,它会按预期工作:
struct BarView : View {
var body: some View {
Color.purple
.relativeWidth(0.5)
.frame(width: 200, height: 200)
}
}
我需要 View 在其容器内灵活而不指定框架。我知道有 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)
}
}
关于swiftui - 使用 SwiftUI 的 relativeWidth 仅在框架 View 内有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876442/