gpt4 book ai didi

swift - 如何在SwiftUI中的GeometryReader中定义变量

转载 作者:行者123 更新时间:2023-12-03 09:22:34 25 4
gpt4 key购买 nike

我想根据 View 的大小计算 View 内部形状的线宽。通过查看StackOverflow上的各种帖子,我认为解决方案是使用像这样的GeometryReader:

struct MyView: View {
var body: some View {
GeometryReader { geometry in
// Here goes your view content,
// and you can use the geometry variable
// which contains geometry.size of the parent
// You also have function to get the bounds
// of the parent: geometry.frame(in: .global)
}
}
}

我的问题是,如何在GeometryReader构造中定义用于 View 的变量?我试图在“GeometryReader {geometry in”行之后直接放置一个var语句,但这会导致编译器错误。

最佳答案

这似乎是一个与功能生成器相关的错误(自Beta 3开始),我建议就此提交反馈。

我一直在使用的解决方法是在带有显式返回的单独方法中使用GeometryProxy


var body: some View {
GeometryReader { proxy in
self.useProxy(proxy)
}
}

func useProxy(_ proxy: GeometryProxy) -> some View {
var width = proxy.size.width
return VStack {
// use width in here
}
}

关于swift - 如何在SwiftUI中的GeometryReader中定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57065925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com