如何在 SwiftUI 中访问父框架
How to access parents frame in SwiftUI
仍在使用 SwiftUI,但我遇到了问题。
我创建了一个带有动态框架的图像,我想要一个标签,它需要是图像的一半宽度(例如图像宽度 = 300;标签宽度 150)
在 UIKit 中,我应该编写如下代码:
Label.widthAnchor.constraint(image.widthAnchor, multiplier: 1/2).isActive = true
我在 SwiftUI 中尝试了类似的东西:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder").frame(width: Image.frame.width/2, height: 30)
但这行不通。
我该怎么办?
为什么不为两者都设置硬尺寸:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder")
.frame(width: UIScreen.main.bounds.width/2, height: 30)
如果你想在一个地方改变组件的整体大小,你可以这样做:
struct MyView : View {
private var compWidth: CGFloat { UIScreen.main.bounds.width }
var body: some View {
VStack {
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: compWidth, height: compWidth)
Text("Placeholder")
.frame(width: compWidth/2, height: 30)
}
}
}
或者,对于更优雅的方法,您可以 look into GeometryReader
。
仍在使用 SwiftUI,但我遇到了问题。 我创建了一个带有动态框架的图像,我想要一个标签,它需要是图像的一半宽度(例如图像宽度 = 300;标签宽度 150)
在 UIKit 中,我应该编写如下代码:
Label.widthAnchor.constraint(image.widthAnchor, multiplier: 1/2).isActive = true
我在 SwiftUI 中尝试了类似的东西:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder").frame(width: Image.frame.width/2, height: 30)
但这行不通。
我该怎么办?
为什么不为两者都设置硬尺寸:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder")
.frame(width: UIScreen.main.bounds.width/2, height: 30)
如果你想在一个地方改变组件的整体大小,你可以这样做:
struct MyView : View {
private var compWidth: CGFloat { UIScreen.main.bounds.width }
var body: some View {
VStack {
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: compWidth, height: compWidth)
Text("Placeholder")
.frame(width: compWidth/2, height: 30)
}
}
}
或者,对于更优雅的方法,您可以 look into GeometryReader
。