数组索引超出了cellForRowAtIndexPath的范围

时间:2015-01-21 04:22:07

标签: ios swift

在我的LeftViewController中,它是滑出菜单,有桌面视图 我正在为每个变量创建表头,它将应用于表格单元格

var locals:[Local]=[Local(title: "Market",image:"ic_cars_black_24dp.png"),
                   Local(title: "Compare", image: "ic_bar_chart_24dp.png"),
                   Local(title: "Wishes",image: "ic_fantasy_24dp.png"),
                   Local(title: "Buy",image: "ic_put_in_24dp.png")]

var globals:[Global]=[Global(title: "Auction Latest",image:"ic_cars_black_24dp.png"),
                   Global(title: "Auction Past", image: "ic_bar_chart_24dp.png"),
                   Global(title: "Auction Recent",image: "ic_fantasy_24dp.png"),
                   Global(title: "Buy",image: "ic_put_in_24dp.png")]

这些是与UITableView相关的函数

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.locals.count + self.globals.count
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerMenuCell = tableView.dequeueReusableCellWithIdentifier("HeaderMenuCell") as HeaderMenuCell

    switch(section){
    case 0:
        headerMenuCell.headerMenuLabel.text="Local"
    case 1:
        headerMenuCell.headerMenuLabel.text="Auction"
    default:
        headerMenuCell.headerMenuLabel.text="Others"
    }

    return headerMenuCell
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as Cell
    switch(indexPath.section){
    case 0:
        cell.configureForLocal(locals[indexPath.row])
    case 1:
        cell.configureForGlobal(globals[indexPath.row])
    default:
        cell.textLabel?.text="Others"
    }
    return cell
}

这是我的Cell类

class Cell: UITableViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageNameLabel: UILabel!

func configureForLocal(locals: Local) {
    imageView.image = UIImage(named: locals.image)
    imageNameLabel.text = locals.title
}

func configureForGlobal(globals: Global) {
    imageView.image = UIImage(named: globals.image)
    imageNameLabel.text = globals.title
}

}

请帮忙,为什么我的数组索引超出范围?

1 个答案:

答案 0 :(得分:3)

tableView:numberOfRowsInSection:有一个section参数,它是想要行计数的部分 - 你需要返回指定部分的正确计数,而不是所有部分的总计数。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0: return locals.count
    case 1: return globals.count
    default: fatalError("unknown section")
    }
}

否则它看起来很好。