确定实例在Swift运行时是否具有可设置属性

时间:2014-09-17 05:59:40

标签: ios objective-c swift introspection

我正在将旧代码移植到Swift。我写了一个自定义输入视图,它适用于我的某些自定义视图。这是我用来附加输入视图的便捷方法:

+ (POGramophoneView *)attachToView:(UIView *)view delegate:(id)delegate
{
    if ([view.inputView isKindOfClass:self]) return (POGramophoneView *)view.inputView;

    POGramophoneView *gramophone = [[POGramophoneView alloc] initWithFrame:CGRectMake(0, 0, 1024, 267)];

    gramophone.attachedView = view;

    NSAssert([view respondsToSelector:@selector(setInputView:)], @"Gramophone view %@ cannot attach to %@ because it does not respond to setInputView:", gramophone, view);

    // This line
    [view performSelector:@selector(setInputView:) withObject:gramophone];

    [view reloadInputViews];

    return gramophone;
}

由于inputView的{​​{1}}是只读的,我必须检查传递给我的视图是否可以设置输入视图。我不知道如何将标记行移植到Swift。如何检查传递的视图是否已将UIView声明为可设置?

inputView

1 个答案:

答案 0 :(得分:1)

Swift确实提供了将字符串文字转换为 Selector 数据类型的函数。你可以像这样写

if view.respondsToSelector(Selector("setInputView:")) {
    // To call the selector use KVO technique.
    view.setValue(gramophone, forKey:"inputView");
}