【问题标题】:How to set height and width in proportion with superview in SwiftUI?如何在 SwiftUI 中设置与 superview 成比例的高度和宽度?
【发布时间】:2020-02-05 11:10:12
【问题描述】:

我想知道是否可以根据SwiftUI中的superview将heightwidth按比例调整到任何UIControl

正如我们所做的那样:

let txtFld = UITextField()
txtFld.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.view.frame.width/2, height: self.view.frame.height*0.1))

我知道我们可以通过使用Spacer().paddingedgeInsets 以某种方式实现调整宽度。但是height 呢?我看过很多SwiftUI 的教程,height 到处都是静态的。即使在苹果的网站上。 SwiftUI Tutorials

如果有人知道如何设置与视图高度成比例的高度,请在此处分享。因为在某些时候我们需要这样。例如。如果需要根据设备高度制作按钮。 (假设 iPhone SE = 40,iPhone 8P = 55,iPhone X = 65)

【问题讨论】:

标签: ios swift xcode swiftui xcode11


【解决方案1】:

您可以使用GeometryReader 从父级获取该信息:

struct MyView: View {
    var body: some View {
        GeometryReader { geometry in
           /*
             Implement your view content here
             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)
           */
        }
    }
}

您可以有一个自定义结构 View 并将其几何体绑定到一个变量,以使其几何体可以从 View 本身访问。

- 示例:

首先定义一个名为 GeometryGetter 的视图(归功于 @kontiki):

struct GeometryGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        return GeometryReader { geometry in
            self.makeView(geometry: geometry)
        }
    }

    func makeView(geometry: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = geometry.frame(in: .global)
        }

        return Rectangle().fill(Color.clear)
    }
}

然后,获取文本视图(或任何其他视图)的边界:

struct MyView: View {
    @State private var rect: CGRect = CGRect()

    var body: some View {
        Text("some text").background(GeometryGetter($rect))

        // You can then use rect in other places of your view:
        Rectangle().frame(width: 100, height: rect.height)
    }
}

【讨论】:

  • @VRAwesome 我添加了一个示例。检查一下。
  • 这看起来是一个绝妙的主意,但对我来说(Xcode 11.2.1)它在self.rect = geometry.frame(in: .global) 上崩溃,并出现错误“前提条件失败:无效输入索引:1”
  • 我还没有更新我的 Xcode,我会在完成后检查问题并通知你。我希望你能在这个想法的帮助下自己做到这一点。 ;) @Grimxn
猜你喜欢
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多