Skip to content

Instantly share code, notes, and snippets.

@danwood
Created January 14, 2025 01:49
Show Gist options
  • Save danwood/c53ede641cf5d95d110f3f8d480bba33 to your computer and use it in GitHub Desktop.
Save danwood/c53ede641cf5d95d110f3f8d480bba33 to your computer and use it in GitHub Desktop.
SwiftUI View minimumFontWidth function and testing code
//
// ContentView.swift
// ViewThatfits
//
// Created by Dan Wood on 1/13/25.
//
import SwiftUI
struct TextCondenser<Content: View>: View {
@ViewBuilder var content: Content
var body: some View {
ViewThatFits {
content.fontWidth(.standard) // 0.0 value
content.fontWidth(.condensed) // -0.2 value
content.fontWidth(.compressed) // -0.3 value
content.fontWidth(.compressed) // last resort, fixed size, so container might want to deal with overflow
.fixedSize()
}
}
}
extension View {
/// Allow font to be `.condensed` a bit, or `.compressed` even further.
///
/// Can be used instead of `minimumScaleFactor()` or in conjunction with it, though scaling is applied only if no room after wrapping to multiple lines
///
/// - Parameter width: a `Font.width` you allow the font to shrink to. We don't use `.expanded`.
@inlinable nonisolated public func minimumFontWidth(_ width: Font.Width = .standard) -> some View {
ViewThatFits {
self // start out with standard font width
if width.value <= Font.Width.condensed.value {
self.fontWidth(Font.Width.condensed)
if width.value <= Font.Width.compressed.value {
self.fontWidth(Font.Width.compressed)
}
}
}
}
}
struct ViewThatFitsByLayoutDemo: View {
@State var width: CGFloat = 100
var body: some View {
Slider(value: $width, in: 30 ... 500)
.padding()
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumFontWidth(.compressed)
.frame(width: width)
.border(.blue)
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumScaleFactor(0.5)
.minimumFontWidth(.compressed)
.frame(width: width)
.border(.blue)
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumFontWidth(.compressed)
.minimumScaleFactor(0.5)
.frame(width: width)
.border(.blue)
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumFontWidth(.condensed)
.frame(width: width)
.border(.blue)
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumScaleFactor(0.5)
.minimumFontWidth(.condensed)
.frame(width: width)
.border(.blue)
Text("The quick brown fox jumps over the lazy dog")
.fixedSize()
.minimumFontWidth(.condensed)
.minimumScaleFactor(0.5)
.frame(width: width)
.border(.blue)
}
}
#Preview{
ViewThatFitsByLayoutDemo()
}
struct ContentView: View {
var body: some View {
ViewThatFitsByLayoutDemo()
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment