ios - 根据 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 添加一个层间类
解决方案
是否可以根据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()
}
}
所以现在你已经有了两个(或者更多)包含在OldSwiper
and中的滑动行为的实现NewSwiper
,并且你的基类根据它运行的环境来决定使用哪一个。
BaseTableViewCell
当然,您可以跳过整个协议,将新旧行为都构建到if
. 不过,使用协议和辅助类会更好,因为它将所有特定于版本的内容保存在单独的类中。它还使您的代码更加灵活——如果您想在未来为 iOS 14.0 及更高版本做一些不同的事情,那么进行更改只需创建一个新的SwipingProtocol
实现即可。
推荐阅读
- javascript - 使用 Javascript 或 Jquery 过滤或搜索 JSON 树数据并返回与搜索字符串或字符匹配的树
- file - 使用 AppleScript 查找和替换文本文件中的多个实例
- reactjs - 导入反应图时,Jest 因“未定义自我”而失败
- javascript - 如何使用 globalCompositeOperation 绘制不同的图像
- c++ - C++、RapidXML:解析大文件
- kotlin - Kotlin 中的内联构造函数是什么?
- sql - PL/SQL 游标声明问题?
- python - 通过 OpenCV 的 m3u8 流中的 NAL 单元大小无效
- python - 从 URL Python 读取和解析 HTML - 高效的内存使用
- data-structures - 哈希中的哪种冲突解决方案本质上是安全的,不会生成 0 增量