之前已经说过了,寻求优雅的最佳捷径就是细品苹果的代码。
1. 细品苹果的代码
下面这段代码,写过富文本的肯定都不陌生:
NSAttributedString.Key.foregroundColor
其中的Key
就是一个 struct:
extension NSAttributedString {
public struct Key : Hashable, Equatable, RawRepresentable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
foregroundColor
是NSAttributedString.Key
扩展的属性。
extension NSAttributedString.Key {
/************************ Attributes ************************/
@available(iOS 6.0, *)
public static let foregroundColor: NSAttributedString.Key // UIColor, default blackColor
}
2. 优雅实践
举个例子,想必不少人实际开发中都添加过自定义字体,添加完后,可以直接使用,如:
let font = UIFont.init(name: "CustomFontName", size: 20)
这样写没问题,但是硬编码着实有点蛋疼。
于是仿照苹果的NSAttributedString.Key.foregroundColor
践行了一波优雅:
extension UIFont {
struct Name {
}
}
extension UIFont.Name {
static let SFProText_Heavy = "SFProText-Heavy"
static let SFProText_LightItalic = "SFProText-LightItalic"
static let SFProText_HeavyItalic = "SFProText-HeavyItalic"
}
但我觉得没必要照搬,所以稍微改了一下结构:
extension UIFont {
struct Name {
static let SFProText_Heavy = "SFProText-Heavy"
static let SFProText_LightItalic = "SFProText-LightItalic"
static let SFProText_HeavyItalic = "SFProText-HeavyItalic"
}
}
使用都是一样的:
let font = UIFont.init(name: UIFont.Name.SFProText_Heavy, size: 20)
爽不爽?
网友评论