Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created June 4, 2020 17:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khanlou/a9f72f01ae38656a935b6f11265c14ea to your computer and use it in GitHub Desktop.
Save khanlou/a9f72f01ae38656a935b6f11265c14ea to your computer and use it in GitHub Desktop.
import SwiftUI
enum ScalableFont {
case system(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default)
case custom(_ name: String, size: CGFloat)
var size: CGFloat {
switch self {
case let .system(size: size, weight: _, design: _):
return size
case let .custom(_, size: size):
return size
}
}
func makeFont(withScaledSize scaledSize: CGFloat) -> Font {
switch self {
case let .system(size: _, weight: weight, design: design):
return .system(size: scaledSize, weight: weight, design: design)
case let .custom(name, size: _):
return .custom(name, size: scaledSize)
}
}
}
struct ScaledFontModifier: ViewModifier {
@Environment(\.sizeCategory) var sizeCategory
var scalableFont: ScalableFont
func body(content: Content) -> some View {
let scaledSize = UIFontMetrics.default.scaledValue(for: scalableFont.size)
return content.font(scalableFont.makeFont(withScaledSize: scaledSize))
}
}
extension View {
func scalableFont(_ scalableFont: ScalableFont) -> some View {
return self.modifier(ScaledFontModifier(scalableFont: scalableFont))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment