Proportional height (or width) in SwiftUI

后端 未结 1 1577
甜味超标
甜味超标 2020-12-11 00:11

I started exploring SwiftUI and I can\'t find a way to get a simple thing: I\'d like a View to have proportional height (basically a percentage of its parent\'s height). Let

相关标签:
1条回答
  • 2020-12-11 00:40

    You can make use of GeometryReader. Wrap the reader around all other views and use its closure value metrics to calculate the heights:

    let propHeight = metrics.size.height * 0.43
    

    Use it as follows:

    import SwiftUI
    
    struct ContentView: View {
        var body: some View {
            GeometryReader { metrics in
                VStack(spacing: 0) {
                    Color.red.frame(height: metrics.size.height * 0.43)
                    Color.green.frame(height: metrics.size.height * 0.37)
                    Color.yellow
                }
            }
        }
    }
    
    import PlaygroundSupport
    
    PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
    
    0 讨论(0)
提交回复
热议问题