Created
March 1, 2017 08:08
-
-
Save elm4ward/c9c37b771377288acc0275c477cd91e3 to your computer and use it in GitHub Desktop.
Using iOS FontStyles with different weights and scales
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 UIKit | |
import PlaygroundSupport | |
extension UIFont { | |
static func font(for style: UIFontTextStyle, | |
atScale scale: CGFloat = 1, | |
usingFont fontInSize: ((CGFloat) -> UIFont)? = nil) -> UIFont { | |
switch (fontInSize, scale) { | |
// in case we provide a way to deliver a different UIFont for a size | |
// we calculate the preferredFont | |
case let (fontInSize?, scale): | |
let size = UIFont.preferredFont(forTextStyle: style).pointSize * scale | |
return fontInSize(size) | |
// scale only | |
case let (_, scale) where scale != 1: | |
let size = UIFont.preferredFont(forTextStyle: style).pointSize * scale | |
return UIFont.systemFont(ofSize: size) | |
// as default we use preferredFont | |
default: | |
return UIFont.preferredFont(forTextStyle: style) | |
} | |
} | |
} | |
protocol StyleableText: class { | |
func styleFont(_ font: UIFont) | |
} | |
extension StyleableText { | |
/// Shortcut for setting the UIFont in UIFontTextStyle. | |
/// When providing a `usingFont` Closure, the font can be changed. | |
/// | |
/// // setting default | |
/// label.setTextStyle(.title1) | |
/// | |
/// // setting scale and font | |
/// label.setTextStyle(.title1, atScale: 1.5, usingFont: UIFont.boldSystemFont) | |
/// | |
/// - parameter style: UIFontTextStyle | |
/// - parameter atScale: CGFloat, default is 1 | |
/// - parameter usingFont: ((CGFloat) -> UIFont)?, default is nil | |
/// - returns: Void | |
func setTextStyle(_ style: UIFontTextStyle, | |
atScale scale: CGFloat = 1, | |
usingFont fontInSize: ((CGFloat) -> UIFont)? = nil) { | |
styleFont(UIFont.font(for: style, atScale: scale, usingFont: fontInSize)) | |
} | |
} | |
extension UILabel: StyleableText { | |
func styleFont(_ font: UIFont) { | |
self.font = font | |
} | |
} | |
extension UITextView: StyleableText { | |
func styleFont(_ font: UIFont) { | |
self.font = font | |
} | |
} | |
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30)) | |
label.setTextStyle(.title1, atScale: 1, usingFont: UIFont.boldSystemFont) | |
label.text = "Test" | |
label.backgroundColor = .white | |
PlaygroundPage.current.liveView = label |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment