问题
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