首页 > 解决方案 > 支持 iOS 12 和 13 时的 UITableView 和 Diffable 数据源

问题描述

我在我的项目中实现了 UITableView Diffable Datasource。它在 IOS 13 中运行良好。当我在 iOS 13 版本以下运行此应用程序时,它会警告我它仅在 ios 13 上可用。所以我正在尝试为低于 iOS 13 的版本实现 UITableView。

UITableView 代码已完成,但我在 iOS 13 上遇到了这个问题。

@available(iOS 13.0, *)
typealias UserDataSource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>
@available(iOS 13.0, *)
typealias UserSnapshot = NSDiffableDataSourceSnapshot<TblSection, YoutubeVideoModel>

在这里,我声明数据源变量

class SearchViewController: UIViewController {
    @available(iOS 13.0, *)
    var datasource: UserDataSource! //Stored properties cannot be marked potentially unavailable with '@available'
    }

初始化数据源和快照

 @available(iOS 13.0, *)
    func configureDatasource(){
         datasource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>(tableView: searchTblView, cellProvider: { (tableView, indexPath, modelVideo) -> VideoTableViewCell? in
        self.configurationCell(indexPath: indexPath)
    })
    }

    @available(iOS 13.0, *)
    func createSnapshot(users: [YoutubeVideoModel]){
    var snapshot = UserSnapshot()
    snapshot.appendSections([.first])
    snapshot.appendItems(users)
    datasource.apply(snapshot, animatingDifferences: true)
      } 

我在声明数据源时遇到此错误,请帮助谢谢。

//Stored properties cannot be marked potentially unavailable with '@available'

我在collectionview上也面临同样的问题。

标签: swiftuitableviewuicollectionviewios13uitableviewdiffabledatasource

解决方案


我们可以在计算属性上使用@available。但是,lazy变量被视为计算属性,因此您也可以在它们上使用 @available。这具有删除额外存储属性的样板和强制转换的好处 - 事实上,它不会在您的 iOS 10 之前的代码中留下该属性的证据。

您可以像这样简单地声明它:

@available(iOS 13.0, *)
lazy var datasource = UserDataSource()

您可以查看此要点以获取更多信息 https://gist.github.com/YogeshPateliOS/b2b13bfe5f7eef5cd7fa4a894cd35d5a


推荐阅读