如何在Swift中遵循Objective-C协议并具有只读属性

4

我们目前在项目中使用这个库:https://github.com/OliverLetterer/SLExpandableTableView

如何在Swift中符合UIExpandingTableViewCell协议?

以下是示例代码...

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) {


    }
}

是因为UIExpansionStyle没有使用NS_ENUM定义的原因吗?
让我有点困惑。

1
与https://dev59.com/RGAf5IYBdhLWcg3w52Pm相关的内容。 - Mats
1个回答

1

简短回答

在类似这样的情况下使用:

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
    // ...
}

使用枚举简写

你在问题中也提到了是因为UIExpansionStyle的定义没有使用NS_ENUM吗?。实际上,这是完全不同的问题,你可以很容易地在库中修复它,然后进行git push并发起pull request。

由于枚举没有像下面这样定义,所以你不能使用.Collapsed简写。

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

然后在Swift中执行以下操作:

var _expansionStyle:UIExpansionStyle = UIExpansionStyle.Collapsed

已编译、链接、构建并运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接