gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:16:18 25 4
gpt4 key购买 nike

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

+ (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;
}

由于 UIViewinputView 是只读的,我必须检查传递给我的 View 是否可以设置输入 View 。我不知道我应该如何将标记的行移植到 Swift。如何检查传递的 View 是否将 inputView 声明为可设置?

class func attachToView(view: UIView, delegate: POGramophoneViewDelegate) -> POGramophoneView {
if view is POGramophoneView {
return view
}

var gramophone = POGramophoneView(frame: CGRectMake(0, 0, 1024, 267))
gramophone.attachedView = view

// set inputview to new gramophone
view.reloadInputViews()

return gramophone
}

最佳答案

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

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

关于ios - 在 Swift 运行时确定实例是否具有可设置的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25883286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com