首页 > 解决方案 > 根据 iOS 版本继承类(swift)

问题描述

是否可以根据iOS的版本继承一个类?

我有代码:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier1", for: indexPath) as! MyCell1
// ....
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier2", for: indexPath) as! MyCell2

对我来说,iOS 版本 <11.0 使用了第三方框架的类,但在 iOS 版本中> = 11.0 使用了标准解决方案。

class MyCell1: BaseTableViewCell {
    // Different code
}

class MyCell2: BaseTableViewCell {
    // Different code
}

// Available for iOS >= 11.0
class BaseTableViewCell: UITableViewCell {
}

// Available for all other versions
class BaseTableViewCell: SwipeTableViewCell {
}

在第三方框架中,我有这个类:

class SwipeTableViewCell: UITableViewCell {
    // Different code
}

实质上,我想为 iOS < 11.0 添加一个层间类

标签: iosswiftinheritance

解决方案


是否可以根据iOS的版本继承一个类?

基类是在编译代码时建立的,而不是在运行时建立的,因此您不能根据代码运行的操作系统版本切换基类。

对我来说,iOS 版本 <11.0 使用了第三方框架的类,但在 iOS 版本中> = 11.0 使用了标准解决方案。

这样做的方法是使用包含而不是继承,这样您就可以在代码运行时将对象配置为所需的行为。把它想象成委托,你有一个帮助对象,可以让你在不创建子类的情况下专门化一个类。

例如,假设您已经BaseTableViewCell基于 定义了您的类UITableViewCell,如您所示:

// Available for iOS >= 11.0
class BaseTableViewCell: UITableViewCell {
}

但也许早于 11.0 的 iOS 版本没有您想要的与滑动相关的某些功能,因此您首先创建一个协议来声明提供您需要添加的行为的函数:

protocol SwipingProtocol {
    func swipe()
}

...并创建实现该协议中的功能的类

class OldSwiper : SwipingProtocol {
    func swipe() { // put your < 11.0 swiping code here }
}

class NewSwiper : SwipingProtocol {
    func swipe() { // put your >= 11.0 swiping code here }
}

...最后为您的基类添加对它的支持:

class BaseTableViewCell: UITableViewCell {
    var swiper : SwipingProtocol

    init() {
        if systemVersion < 11.0 {
            swiper = OldSwiper()
        }
        else {
            swiper = NewSwiper()
        }
    }

    func swipe() {
        swiper.swipe()
    }
}

所以现在你已经有了两个(或者更多)包含在OldSwiperand中的滑动行为的实现NewSwiper,并且你的基类根据它运行的环境来决定使用哪一个。

BaseTableViewCell当然,您可以跳过整个协议,将新旧行为都构建到if. 不过,使用协议和辅助类会更好,因为它将所有特定于版本的内容保存在单独的类中。它还使您的代码更加灵活——如果您想在未来为 iOS 14.0 及更高版本做一些不同的事情,那么进行更改只需创建一个新的SwipingProtocol实现即可。


推荐阅读