How to use GeometryReader without it filling the View

喜你入骨 提交于 2020-02-23 04:20:28

问题


This is the layout I'm aiming for.

import SwiftUI
import PlaygroundSupport

struct TestView: View {

    let text: String

    var body: some View {
        Text(self.text)
    }
}

struct ContentView: View {
    var body: some View {
        ZStack {
            TestView(text: "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla")
                .frame(width: 250)
                .background(Color.red)
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

But I also want to use the GeometryReader and when I put the Text inside the GeometryReader it will take up the full height.

import SwiftUI
import PlaygroundSupport

struct TestView: View {

    let text: String

    var body: some View {
        GeometryReader { reader in
            Text(self.text)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ZStack {
            TestView(text: "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla")
                .frame(width: 250)
                .background(Color.red)
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

How can I get around this?


回答1:


WARNING ⚠️ : This is when Geomtery reader couldn't help with me with geometry and I started to bang my head against the wall

Here's what you can do:

struct ContentView: View {

    var text =  "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla"
    var width : CGFloat = 250

    var height: CGFloat {
        var size : CGFloat
        let chars = self.width / 14  // assuming width of 1 character is 14 which is the case by default for Text view
        let lines = CGFloat(text.count) / chars
        size = CGFloat(14 * (lines + 1))
        return size
    }

    var body: some View {
        ZStack {
            TestView(text: text)
            .frame(width: width, height: height)
            .background(Color.red)
        }
    }
}

Set the height of the TestView manually by using height as a computed property.

A background story on how I estimated default font height

Press shift + command + 4 Use the pointer and find the difference between the relative y positions



来源:https://stackoverflow.com/questions/60227960/how-to-use-geometryreader-without-it-filling-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!