Jonnny Jonnny - 1 month ago 6
Swift Question

index out of range for multiple sections

I'm trying to have a tableview with some players listed in two sections.
section 1 is players currently playing and section 2 is for substitutes. I have one data set with all the players on.

How I went about this is I created two sections

let sections = ["playing", "subs"]


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


I had hoped that this would put the 1st 11 players in my array in the playing section, which it does seem to, but, as I scroll through the table it crashes as I come to the next section I believe. I'm assuming that each section of data must therefore start with an indexPath of 0? and I only have one set of data.

As my app works I want to be able to reorder people across the two sections as they are playing or are subbed. What's the iOS appropriate way to achieve this?

This is my cell for row at indexpath method:

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

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


and it crashes here with EXC_BAD_INSTRUCTION. Happy to update my question with any more info, I'm relatively new to iOS and not attempted moving rows before

Answer

I think it is better to create 3 separate NSMutableArrays. 1st for totalPlayers. 2nd for "playing". and 3rd for "subs".

Then you add/remove players accordingly from totalPlayers. Then you can properly return [array count] in the numberOfRowsInsection.

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

Doing the math in this delegate is bad practice really. Because you need to handle all values and in your case, the app will crash if the player-11 becomes less than 0.

Comments