简体   繁体   中英

Tableview contents getting reordered when scrolled Swift

I have created a tableview with tableview cells in it. I am able to list the contents on the different rows of the table view (I am listing the songs from device on the rows of tableview). The code snippet for this is given below.

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

 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! hostTableViewCell    //hostTableViewCell is the custom cell class

    cell.backgroundColor = UIColor.clearColor()

    print("\(songList[indexPath.section + StaticThing.timesCalled].songTitle)")

    cell.clientCellLabel!.text = songList[indexPath.section + StaticThing.timesCalled].songTitle

    copyOfAllSongsArray.append(songList[indexPath.section + StaticThing.timesCalled].songTitle)    // Taking text of the cells in an array

    cell.detailTextLabel!.text = "\(songList[indexPath.section + StaticThing.timesCalled].artistName)"

    StaticThing.doSomething()

    if (StaticThing.timesCalled == songList.count){

        StaticThing.timesCalled = 0

    }

    return cell;

}

The tableview upon loading for the first time is showing its contents. However, when the page is scrolled every time, the contents of the tableview gets reordered. Every time the table is scrolled, the content gets reordered in a random way. How to fix this issue?.

Your code makes no sense. You're using some variable timesCalled to index into your data array? The order in which the system fetches cells in cellForRowAtIndexPath is not guaranteed. You need to use the section and row numbers passed to you in the indexPath in order to figure out which item to return, not use the number of times the method is called.

The logic for your cellForRowAtIndexPath needs to be redone. It's completely wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM