2

In UIKit it was relatively easy to calculate the needed size of a string with a given Font. How can I achieve this in SwiftUI? It seems hat the needed properties on Text and Font are missing to convert objects to SwiftUI and do the calculation here.

Here is the code I have so far: Problem: I don't want to use a hard coded Font (and not UIFont at all).

private func determineTruncation(_ geometry: GeometryProxy) {

        // Calculate the bounding box we'd need to render the

        // text given the width from the GeometryReader.

        let total = text.boundingRect(

            with: CGSize(

                width: geometry.size.width,

                height: .greatestFiniteMagnitude

            ),

            options: .usesLineFragmentOrigin,

            attributes: [.font: UIFont.systemFont(ofSize: 16)],

            context: nil

        )


 

        if total.size.height > geometry.size.height {

            self.truncated = true

        }

    }
netshark1000
  • 7,245
  • 9
  • 59
  • 116
  • Would you show code where/why (what for) do you need that size? `Cause in majority of cases it is either not needed at all or achieved by different instruments. – Asperi Jul 20 '20 at 09:53
  • I added the code I have so far – netshark1000 Jul 20 '20 at 10:38
  • For the truth I don't see the reason of this code... Might be this [How to set relative width in a HStack embedded in a ForEach in SwiftUI?](https://stackoverflow.com/a/62993223/12299030) topic will be helpful for you as approach demo. – Asperi Jul 20 '20 at 10:42
  • The reason I wrote this was: If my Text needs to much space I want to put it in a ScrollView. Otherwise not – netshark1000 Jul 20 '20 at 11:14
  • 2
    In such case it is better to put it inside ScrollView, but disable scrolling if not needed to scroll. It is already solved in [SwiftUI: Make ScrollView scrollable only if it exceeds the height of the screen](https://stackoverflow.com/a/62466397/12299030) – Asperi Jul 20 '20 at 11:18

0 Answers0