首页 > 解决方案 > 如何在 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)

但这不起作用。

我该怎么办?

标签: swiftinheritanceconstraintswidthswiftui

解决方案


为什么不为两者设置硬尺寸:

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)
         }
     }
}

或者,对于更优雅的方法,您可以查看 GeometryReader.


推荐阅读