将字体设置为响应 :#selector(setter:object.font) 的任何对象

Setting font to any object that responds to :#selector(setter:object.font)

我正在尝试重写这个 Objective-C 方法,它工作得很好

+ (void)setFontName:(NSString*)fontName onObject:(id)object {
    if ([object respondsToSelector:@selector(setFont:)]) {
        UIFont* font = [UIFont fontWithName:fontName size:((UIFont *)[object font]).pointSize];
        [object setFont:font];
    }
}

在Swift中:

public static func setFontRewriting(fontName: String, object: AnyObject) {
    if object.responds(to:#selector(setter: object.font)) {
        let currentFont: UIFont = object.font
        let fontToSet = UIFont(name: fontName, size: currentFont.pointSize)
        object.font = fontToSet //doesn't work, getting various syntax errors
    }
}

即使一个对象响应这个选择器,我也不能给它设置字体。 object.setFont 也不起作用。有什么建议吗?

您可以执行以下操作:

object.setValue(fontToSet, forKey: "font")