如何在Swift中使用具有只读属性的Objective-C协议

凯兰克斯

我们目前正在我们的项目中使用此库... https://github.com/OliverLetterer/SLExpandableTableView

如何遵循UIExpandingTableViewCellSwift中协议?

这是副本...

typedef enum {
    UIExpansionStyleCollapsed = 0,
    UIExpansionStyleExpanded
} UIExpansionStyle;

@protocol UIExpandingTableViewCell <NSObject>

@property (nonatomic, assign, getter = isLoading) BOOL loading;

@property (nonatomic, readonly) UIExpansionStyle expansionStyle;
- (void)setExpansionStyle:(UIExpansionStyle)style animated:(BOOL)animated;

@end

我尝试了以下方法,但仍然说不符合要求...

class SectionHeaderCell: UITableViewCell, UIExpandingTableViewCell {

    @objc var loading: Bool
    @objc private(set) var expansionStyle: UIExpansionStyle

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setExpansionStyle(style: UIExpansionStyle, animated: Bool) {


    }
}

是否由于不使用NS_ENUM定义UIExpansionStyle的方式?

困惑

迅捷建筑师

简短答案

本着以下精神使用:

var loading:Bool {
    @objc(isLoading) get {
        return self._isLoading
    }
    set(newValue){
        _isLoading = newValue
    }
}

长答案

创建一个新的新项目,执行一个pod init,添加Podfile与下面类似的项目,然后运行pod install

platform :ios, '8.0'
target 'SO-32254051' do
pod 'SLExpandableTableView'
end

在Swift中使用Objective-C命名属性属性

developer.apple.com文档中所述:

必要时,使用@objc(<#name#>)属性为属性和方法提供Objective-C名称。

符合性的问题仅在于:自定义getter名称。

完整的解决方案

采用协议

class TableViewCell: UITableViewCell, UIExpandingTableViewCell { ... }

定义本地存储

var _isLoading:Bool = false
var _expansionStyle:UIExpansionStyle = UIExpansionStyle(0)

实现命名的getter和setter

var loading:Bool {
    @objc(isLoading) get {
        return self._isLoading
    }
    set(newValue){
        _isLoading = newValue
    }
}

private(set) var expansionStyle:UIExpansionStyle {
    get{
        return _expansionStyle
    }
    set(newValue){
        _expansionStyle = newValue
    }
}

func setExpansionStyle(style: UIExpansionStyle, animated: Bool) {
    self.expansionStyle = style
    // ...
}

使用Enum速记

您还提到这是否是因为不使用NS_ENUM定义UIExpansionStyle的方式?在你的问题。实际上,这实际上是一个完全不同的问题,您可以轻松地在库中修复该问题并提出git push并请求。

由于enum未将定义为波纹管,因此​​无法使用.Collapsed速记。

typedef NS_ENUM(NSUInteger, UIExpansionStyle) {
    UIExpansionStyleCollapsed = 0,
    UIExpansionStyleExpanded
};

然后在Swift中执行此操作

var _expansionStyle:UIExpansionStyle = UIExpansionStyle.Collapsed

编译,链接,构建和运行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章