Created
March 3, 2018 05:11
-
-
Save ignatovSA/d7978e748b7a0e57201ffa479f98afa3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
public struct TextStyle { | |
let font: UIFont | |
let color: UIColor | |
let kerning: CGFloat? | |
let lineHeight: CGFloat? | |
} | |
extension TextStyle { | |
init(fontName: String, pointSize: CGFloat, color: UIColor, | |
kerning: CGFloat, lineHeight: CGFloat) { | |
let fontDescriptor = UIFontDescriptor(name: fontName, size: pointSize) | |
let font = UIFont(descriptor: fontDescriptor, size: pointSize) | |
self.init(font: font, color: color, kerning: kerning, lineHeight: lineHeight) | |
} | |
init(font: UIFont, color: UIColor) { | |
self.init(font: font, color: color, kerning: nil, lineHeight: nil) | |
} | |
} | |
// Then concrete TextStyles could be described by extension like fonts/colors. | |
extension TextStyle { | |
static let visibleButton = TextStyle(font: .visibleButton, color: .orangePink) | |
} | |
// TextStyle could be used for NSMutableString configuration | |
extension NSAttributedString { | |
private static func attributes(for textStyle: TextStyle) -> [NSAttributedStringKey: Any] { | |
var attributes: [NSAttributedStringKey: Any] = [ | |
.font: textStyle.font, | |
.foregroundColor: textStyle.color, | |
] | |
if let lineHeight = textStyle.lineHeight { | |
let paragraphStyle = NSMutableParagraphStyle() | |
paragraphStyle.maximumLineHeight = lineHeight | |
attributes[.paragraphStyle] = paragraphStyle | |
} | |
if let kerning = textStyle.kerning { | |
attributes[.kern] = kerning | |
} | |
return attributes | |
} | |
public convenience init(string: String, textStyle: TextStyle) { | |
let attributes = NSAttributedString.attributes(for: textStyle) | |
self.init(string: string, attributes: attributes) | |
} | |
} | |
// TextStyle could be applied directly to text-related entities | |
protocol TextStyleApplicable { | |
func applyPlainStyle(_ textStyle: TextStyle) | |
} | |
extension UILabel: TextStyleApplicable { | |
func applyPlainStyle(_ textStyle: TextStyle) { | |
font = textStyle.font | |
textColor = textStyle.color | |
} | |
} | |
extension UITextField: TextStyleApplicable { | |
func applyPlainStyle(_ textStyle: TextStyle) { | |
font = textStyle.font | |
textColor = textStyle.color | |
} | |
} | |
extension UITextView: TextStyleApplicable { | |
func applyPlainStyle(_ textStyle: TextStyle) { | |
font = textStyle.font | |
textColor = textStyle.color | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment