4

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())

enter image description here

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())

enter image description here

How can I get around this?

Community
  • 1
  • 1
Peter Warbo
  • 11,136
  • 14
  • 98
  • 193

1 Answers1

0

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.

screenshot

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

Tilak Madichetti
  • 4,110
  • 5
  • 34
  • 52