Created
June 4, 2020 17:34
-
-
Save khanlou/a9f72f01ae38656a935b6f11265c14ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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