尝试在 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 似乎正是这里所需要的时,这似乎有点麻烦。有任何想法吗?
Well, .relativeWidth()
beta4 已经消失了...所以我正在更新我的答案。
作为替代方案几何阅读器 https://swiftui-lab.com/geometryreader-to-the-rescue/,这有其自身的不便,在您的情况下,使用 Shape 可能是一个不错的选择。
The 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)