Skip to content

Instantly share code, notes, and snippets.

@mikebernardo
Last active August 3, 2020 12:21
Show Gist options
  • Save mikebernardo/011d9f6839baac40b359e0ad18b4b0d4 to your computer and use it in GitHub Desktop.
Save mikebernardo/011d9f6839baac40b359e0ad18b4b0d4 to your computer and use it in GitHub Desktop.
Example of how to create a Text that shrinks font size when compressed vertically. (Workaround for limitation in SwiftUI)
import SwiftUI
// Workaround for a limitation in SwiftUI's Text view that prevents it
// from shrinking the font size when using `lineLimit`
struct ContentView: View {
let text:String
let bottomRectHeight:CGFloat
var body: some View {
VStack(alignment:.center, spacing:0 ) {
// Use GeometryReader to scale the font size based on height
// of the container
GeometryReader {reader in
Text(self.text)
.font(Font.system(size: 60.0 * reader.size.height / 80))
.minimumScaleFactor(0.15)
.lineLimit(1)
.background(Color.blue)
}
Rectangle()
.strokeBorder()
.foregroundColor(Color.purple)
.frame(maxWidth: .infinity)
.frame(height:self.bottomRectHeight)
}
.frame(width: 100, height: 100)
.background(Color.green)
}
}
struct ContentPreviewWrapper : View {
@State var height:CGFloat = 40.0
var body: some View {
VStack(spacing:20) {
ContentView(text:"Hello world", bottomRectHeight:self.height)
ContentView(text:"150", bottomRectHeight:self.height)
Slider(value:$height, in:0.0...100.0)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentPreviewWrapper()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment