首页 > 解决方案 > 使 numberOfRowsInSection 中的索引超出范围

问题描述

我的 tableView 中有一个奇怪的 cellModel 像这样

   fileprivate enum CellModel {
    case search
    case categories
    case switcher
    case wishes
}

fileprivate enum HeaderModel {
    typealias CellType = CellModel
    case search
    case categories
    case switcher
    case wishes


    var cellModels: [MAWishesViewController.CellModel] {
        switch self {
        case .search: return [.search]
        case .categories: return [.categories]
        case .switcher: return [.switcher]
        case .wishes: return [.wishes]
        }
    }
}

private var wishes = [Wish]()
private var categories = [Category]()

private let models:[CellModel] = [.search, .categories, .switcher, .wishes]
private let HeaderModels: [HeaderModel] = [.search, .categories, .switcher, .wishes]

这是我的委托和数据源方法:)我使用带有枚举的模型,我开始认为这是个坏主意!

    func numberOfSections(in tableView: UITableView) -> Int {
    return models.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  let header = HeaderModels[section]
    switch header {
    case .categories:
        return 1
    case .search:
        return 1
    case .switcher:
        return 1
    case .wishes:
        return self.wishes.count
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let model = HeaderModels[indexPath.section].cellModels[indexPath.row]


    switch model {
    case .search:
        if let cell = tableView.dequeueReusableCell(withIdentifier: SearchTableViewCell.name, for: indexPath) as? SearchTableViewCell {

            return cell
        }
    case .categories:
        if let cell = tableView.dequeueReusableCell(withIdentifier: CategoriesTableViewCell.name, for: indexPath) as? CategoriesTableViewCell {
            cell.collectionView.delegate = self
            cell.collectionView.dataSource = self
            return cell
        }
    case .switcher:
        if let cell = tableView.dequeueReusableCell(withIdentifier: SwitcherTableViewCell.name, for: indexPath) as? SwitcherTableViewCell {

            return cell
        }
    case .wishes:
        if let cell = tableView.dequeueReusableCell(withIdentifier: WishTableViewCell.name, for: indexPath) as? WishTableViewCell {

            let wish = self.wishes[indexPath.row]
            cell.pictureImageView.image = UIImage(named: wish.image!)
            cell.nameLabel.text = wish.name
            cell.descriptionLabel.text = wish.description
            return cell
        }
    }

    return UITableViewCell.init()
}

我得到了“索引超出范围。我只想wishes.count在名为的部分返回.wishes

我也摆脱了cellForRowAt方法中的索引。那么问题可能是什么?

标签: swiftxcodetableview

解决方案


推荐阅读