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

时间:2017-12-13 20:30:19

标签: ios swift selector uifont

我试图重写这个完全正常的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也不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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