索引超出范围的多个部分

时间:2016-10-11 02:05:22

标签: ios swift uitableview

我试图在两个部分中列出一些玩家的桌面视图。 第1部分是正在播放的队员,第2部分是替补队员。我有一个数据集与所有玩家。

我是如何做到这一点的,我创建了两个部分let sections = ["playing", "subs"]

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 11
    } else {
        return players.count - 11
    }
}

我原本希望这会让我的阵列中的前11名选手参加比赛,看起来确实如此,但是,当我滚到桌子时,当我进入下一部分时我会相信它会崩溃。我假设每个数据部分必须以indexPath为0开头?我只有一组数据。

当我的应用程序正常工作时,我希望能够在两个部分重新排序,因为他们正在玩或者是subbed。什么是iOS适当的实现方式?

这是我在indexpath方法中的行的单元格:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = playerTableView.dequeueReusableCellWithIdentifier("MatchPlayerCell")! as! MatchPlayerCell
    cell.configureForMatchPlayer(orderedPlayers[indexPath.row])
    return cell
}

它在EXC_BAD_INSTRUCTION崩溃了。很高兴用更多信息更新我的问题,我对iOS相对较新,并且没有尝试过移动行

4 个答案:

答案 0 :(得分:1)

我认为最好创建3个独立的NSMutableArrays。 totalPlayers的第1名。 "打"。和#34; subs"。

然后你从totalPlayers中相应地添加/删除玩家。然后你可以在numberOfRowsInsection中正确返回[array count]。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return players.count
    } else {
        return subs.count
    }
}

在这个委托中进行数学计算实际上是不好的做法。因为您需要处理所有值,并且在您的情况下,如果播放器-11变得小于0,应用程序将崩溃。

答案 1 :(得分:1)

您没有提供足够的信息来解释崩溃,但作为政策的一般问题,使用单个数组(players)来表示具有两个部分的表的数据是愚蠢的。两节?两个阵列。

否则只是要求麻烦,特别是因为这意味着您的cellForRowAt:必须知道该模型的工作原理。这不合适。模型应该是cellForRowAt:只是愚蠢的。部分?选择相应的数组。行?选择相应的索引。完成。不要试图在cellForRowAt:中成为一个聪明的裤子;你结束了,呃,崩溃了。

答案 2 :(得分:1)

如果你没有超过11名玩家,它将会崩溃..请确保。

答案 3 :(得分:0)

如果你的player有一个属性来确定他是在玩还是子,那么你可以当然使用一个数组,不管它是明智的到这样做取决于你。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return orderedPlayers.filter { $0.playing }.count
    } else {
        return orderedPlayers.filter { !$0.playing }.count
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let player = orderedPlayers.filter { indexPath.section == 0 ? $0.playing : !$0.playing }[indexPath.row]
    let cell = playerTableView.dequeueReusableCellWithIdentifier("MatchPlayerCell")! as! MatchPlayerCell
    cell.configureForMatchPlayer(player)
    return cell
}

你可以通过让看起来像这样有两个数组来实现更简洁:事实上,只有一个数组:

var players: [Player] {
    return orderedPlayers.filter { $0.playing }
}

var subs: [Player] {
    return orderedPlayers.filter { !$0.playing }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return section == 0 ? players.count : subs.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let player = (indexPath.section == 0 ? players : subs)[indexPath.row]
    let cell = playerTableView.dequeueReusableCellWithIdentifier("MatchPlayerCell")! as! MatchPlayerCell
    cell.configureForMatchPlayer(player)
    return cell
}
相关问题