Ios 如何在同一脚本中检索扩展类外部的数据数组
我的应用程序有一个自定义的滚动视图,我的主委托类中有一个数据数组。我还有一个单独的扩展名(在同一个文件中)来处理数据,但我似乎无法访问数据,因为有两个错误Ios 如何在同一脚本中检索扩展类外部的数据数组,ios,swift,xcode,swift5,Ios,Swift,Xcode,Swift5,我的应用程序有一个自定义的滚动视图,我的主委托类中有一个数据数组。我还有一个单独的扩展名(在同一个文件中)来处理数据,但我似乎无法访问数据,因为有两个错误使用未解析的标识符数据: class HomeViewController: UIViewController { fileprivate let data = [ CustomData(title: "Test", image: #imageLiteral(resourceName: "splash_icon"),
使用未解析的标识符数据:
class HomeViewController: UIViewController {
fileprivate let data = [
CustomData(title: "Test", image: #imageLiteral(resourceName: "splash_icon"), url: "clipifyapp.com"),
CustomData(title: "Test2", image: #imageLiteral(resourceName: "done-button"), url: "clipifyapp.com"),
CustomData(title: "Test2", image: #imageLiteral(resourceName: "notificationIcon"), url: "clipifyapp.com")
]
}
extension UIViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/2.5, height: collectionView.frame.width/2)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count // ERROR ONE
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.data = self.data[indexPath.row] // ERROR TWO
return cell
}
}
我是否遗漏了一些明显的内容?您正在扩展UIViewController
,但您不是想扩展HomeViewController
如果扩展UIViewController
,则不会扩展实际包含数据的子类。此外,您将扩展整个应用程序中的每一个UIViewController,这可能不是您想要对UICollectionViewDataSource执行的操作。数据
仅在HomeViewController
中可用,而不在基类UIViewController
替换
extension UIViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
与
数据
在UIViewController
的子类中定义,因此您无法从超类或超类的扩展访问它
extension HomeViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {