Get width of a view using in SwiftUI

前端 未结 2 1830
时光取名叫无心
时光取名叫无心 2020-12-29 09:27

I need to get width of a rendered view in SwiftUI, which is apparently not that easy.

The way I see it is that I need a function that returns a view\'s d

2条回答
  •  萌比男神i
    2020-12-29 10:03

    Getting the dimensions of a child view is the first part of the task. Bubbling the value of dimensions up is the second part. GeometryReader gets the dims of the parent view which is probably not what you want. To get the dims of the child view in question we might call a modifier on its child view which has actual size such as .background() or .overlay()

    struct GeometryGetterMod: ViewModifier {
    
        @Binding var rect: CGRect
    
        func body(content: Content) -> some View {
            print(content)
            return GeometryReader { (g) -> Color in // (g) -> Content in - is what it could be, but it doesn't work
                DispatchQueue.main.async { // to avoid warning
                    self.rect = g.frame(in: .global)
                }
                return Color.clear // return content - doesn't work
            }
        }
    }
    
    struct ContentView: View {
        @State private var rect1: CGRect = CGRect()
        var body: some View {
            let t = HStack {
                // make two texts equal width, for example
                // this is not a good way to achieve this, just for demo
                Text("Long text").overlay(Color.clear.modifier(GeometryGetterMod(rect: $rect1)))
                // You can then use rect in other places of your view:
    
                Text("text").frame(width: rect1.width, height: rect1.height).background(Color.green)
                Text("text").background(Color.yellow)
            }
            print(rect1)
            return t
        }
    }
    

提交回复
热议问题