在哪里放置杂项广泛使用的功能?

ale*_*wis -1 swift

这个问题是否有一个简洁的方法来表示一个分数作为属性字符串?.

我有一个为分数字符串提供字体的函数

func fractionFont() -> UIFont {
    let pointSize = CGFloat(20.0)
    let systemFontDescriptor = UIFont.systemFontOfSize(pointSize, weight: UIFontWeightLight).fontDescriptor()
    let fractionFontDescriptor = systemFontDescriptor.fontDescriptorByAddingAttributes(
    [
        UIFontDescriptorFeatureSettingsAttribute: [
        [
            UIFontFeatureTypeIdentifierKey: kFractionsType,
            UIFontFeatureSelectorIdentifierKey: kDiagonalFractionsSelector,
        ], ]
    ] )
    return UIFont(descriptor: fractionFontDescriptor, size: pointSize)
}
Run Code Online (Sandbox Code Playgroud)

我在其中使用了标签属性 SomeClass

class SomeClass {
    @IBOutlet weak var fractionLabel: UILabel! {
        didSet {
            fractionLabel.text = "1/2"
            fractionLabel.font = fractionFont()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

说我想fractionFont再次使用方法AnotherClass我猜复制代码不是一个好主意.我还被告知在另一篇文章中Singleton谨慎地使用所谓的类,那么最好的方法是什么呢?

  • 谢谢

mip*_*adi 5

我会UIFont用你的fractionFont方法扩展:

extension UIFont {
    class func fractionFont() -> UIFont {
        /* Code here */
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 关于这一点最好的部分是,如果推断出类型,Swift将允许您引用没有类名的类方法.`fractionLabel.font = .fractionFont()` (2认同)