我试图重写这个完全正常的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
也不起作用。有什么建议吗?
答案 0 :(得分:1)
您可以执行以下操作:
object.setValue(fontToSet, forKey: "font")