首页 > 解决方案 > 实现分页后,我在滚动 tableview 时遇到 UIImage 问题

问题描述

目前有一个表格视图,在每个单元格中包含不同的图像,我从一个从 JSON 获取的 URL 下载图像并将其作为 imageviews 图像。我的问题是,在我进行分页调用之后,我刚刚滚动过去的图像变成了一个图像并粘住了,只有新分页的信息才显示正确的信息。

以 JSON 格式提供数据的方式大部分数据包含在对象数组中,其中包含除图像之外的大部分信息。图像在字典中单独给出,该字典获取对象 id 并匹配它,然后为适当的对象提供图像 URL。我在我的网络类中实现了分页,我在其中进行 JSON 下载调用:

func downloadGamesByPlatformIDJSON(platformID: Int?, fields: String?, include: String?, pageURL: String?, completed: @escaping () -> () ) {
        var urlString : String?
        
        if pageURL == nil {
            urlString = "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=\(apiKey)&id=\(platformID!)"
            
            if fields != nil {
                urlString = urlString! + "&fields=" + fields!
            }
            if include != nil {
                
                urlString = urlString! + "&include=" + include!
            }
            
        } else {
            urlString = pageURL!
        }
        print(urlString!)
        let url = URL(string: "\(urlString!)")!
        print(url)
        var requestHeader = URLRequest.init(url: url)
        requestHeader.httpMethod = "GET"
        requestHeader.setValue("application/json", forHTTPHeaderField: "Accept")
        
        URLSession.shared.dataTask(with: requestHeader) { (data, response, error) in
            
            if error != nil {
                print("error = \(error)")
                completed()
            }
            
            if error == nil {
                do {
                    print("error = nil")
                    let json = String(data: data!, encoding: .utf8)
                    
                    print(json)
                    
                    if let jsonDecodedPlatforms = try JSONDecoder().decode(ByPlatformIDData?.self, from: data!) {
                        
                        print(jsonDecodedPlatforms)
                        let decodedJSON = jsonDecodedPlatforms.data?.games
                        self.boxart = jsonDecodedPlatforms.include.boxart
                        self.baseURL = jsonDecodedPlatforms.include.boxart.baseURL
                        self.page = jsonDecodedPlatforms.pages
                        
                        if let parseJSON = decodedJSON {
                     
                          var items = self.games
                            var boxarts = self.imageArray
                            items.append(contentsOf: parseJSON)
                            
                            if self.initialOffset < items.count {
                                self.games = items
                                self.imageArray = boxarts
                                self.initialOffset = items.count
                                
                            } else {
                                self.games = items
                                self.imageArray = boxarts
                            }
                            
                            
                        }
                        
                        
                    }
                    
                    DispatchQueue.main.async {
                        
                        completed()
                        print(data)
                    }
                } catch {
                    print(error)
                }
                
            }
            
        }.resume()
        
    }
    
    
}

所以我要做的是,如果我在最后一个单元格上,我下载下一页数据并将其附加到对象数组中。这似乎工作得很好,但是图像只是单独下载到单元格中,它们不是一组单独的对象。我已经多次尝试获取下载的图像,将其附加到图像数组,将 indexPath.row 中的图像应用到图像视图,然后以与处理其余信息相同的方式处理它。这会导致崩溃,因为它找不到第一个以外的任何索引。我把头发拉出来。我错过了什么?任何帮助表示赞赏。

这是我的其他相关代码:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

 if indexPath.row == (network.games.count - 1) && network.page?.next != nil {
            pageURL = network.page?.next
            
            network.downloadGamesByPlatformIDJSON(platformID: nil, fields: nil, include: nil, pageURL: network.page?.next) {
                print("pagination successful")
                tableView.reloadData()
                
            }
        }

  if frontImageName != nil {

            cell.tableViewCoverImage.loadImage(from: imageUrl) { print("tableViewCoverImage loaded!")
                self.network.imageArray.append(cell.tableViewCoverImage.image)
                self.coverImage = cell.tableViewCoverImage.image!
                cell.tableViewCoverImage.image = self.network.imageArray[indexPath.row]
                
               
            }
        }
        else {
            cell.tableViewCoverImage.image = UIImage(named: "noArtNES")

        }
  
        
        return cell
}
extension UIImageView {
    func loadImage(from url: String, completed: @escaping () -> ()) {
        
        
        
        let imageURL = URL(string: url)
        
        DispatchQueue.global().async { [weak self] in
            
            if let data = try? Data(contentsOf: imageURL!) {
                
                if let image = UIImage(data: data) {
                    
                    DispatchQueue.main.async {
                        self?.image = image
                        completed()
                    }
                }
            }
        }
    }
{
    "code": 200,
    "status": "Success",
    "data": {
        "count": 20,
        "games": [
            {
                "id": 4,
                "game_title": "Star Fox 64",
                "release_date": "1997-06-30",
                "platform": 3,
                "players": 4,
                "overview": "The Lylat system has been invaded!  Join Fox McCloud and his Star Fox team as they fight to save the galaxy from the clutches of the evil Andross.  Travel to many different 3-D worlds.  Battle the enemy in the air and on the ground and listen in as Fox McCloud interacts with a cast of characters.\r\n\r\nSee how it feels to feel what you see!  The N64 Rumble Pak controller accessory instantly transmits all the bumps and blasts during the action.  It’s a new jolt to your game play experience!\r\n\r\n* Four Players compete simultaneously in Vs. mode!\r\n* Game Pak memory saves the top 10 scores!\r\n* Outstanding cinema scenes tell the Star Fox saga!",
                "last_updated": "2018-08-11 15:01:11",
                "rating": "E - Everyone",
                "coop": "No",
                "youtube": "jsEcmfPwnHo",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    6037
                ],
                "genres": [
                    1,
                    8
                ],
                "publishers": [
                    3
                ],
                "alternates": [
                    "Lylat Wars"
                ]
            },
            {
                "id": 42,
                "game_title": "Mario Party",
                "release_date": "1999-02-08",
                "platform": 3,
                "players": 4,
                "overview": "Every game in the main series has a standard Party Mode in which up to four players play through a board, trying to collect as many stars as possible. In every turn, each player rolls a die and progresses on the board, which usually has branching paths. Coins are primarily earned by performing well in a minigame played at the end of each turn. On most boards, players earn stars by reaching a star space and purchasing a star for a certain amount of coins. The star space appears randomly on one of several pre-determined locations and moves every time a star is purchased, usually occupying a blue space.\r\nEvery Mario Party contains at least 50 to almost 110 minigames with a few different types. Four-player games are a free-for-all in which players compete individually. In 2-on-2 and 1-on-3 minigames, players compete as two groups, cooperating to win, even though they are still competing individually in the main game. Some minigames in Mario Party are 4-player co-op, even though it doesn't say it. In most situations, winners earn ten coins each.",
                "last_updated": "2018-07-11 21:05:01",
                "rating": "E - Everyone",
                "coop": "No",
                "youtube": "sScj7MwjHBs",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    3923
                ],
                "genres": [
                    1,
                    2,
                    6,
                    11
                ],
                "publishers": [
                    3
                ],
                "alternates": null
            },
            {
                "id": 68,
                "game_title": "Turok: Dinosaur Hunter",
                "release_date": "1997-03-04",
                "platform": 3,
                "players": 1,
                "overview": "Much like your usual 1st person shooter, although with dinosaurs as your main enemy. Includes 14 high tech weapons, like the Quad Rocket Launcher and the Atomic Fusion Cannon. You control Turok, who must take on the Campaigner and his highly evolved dino's. The objective is to collect pieces of the Chronoscepter, which is the only weapon that can help to destory the Campaigner, and to stop him from using the power of the weapon to destory the Lost Land.",
                "last_updated": "2020-04-16 11:18:30",
                "rating": "M - Mature 17+",
                "coop": "No",
                "youtube": "3AKbul3ILM0",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    4065
                ],
                "genres": [
                    8
                ],
                "publishers": [
                    28
                ],
                "alternates": null
            },
            
            {
                "id": 216,
                "game_title": "Super Mario 64",
                "release_date": "1996-09-29",
                "platform": 3,
                "players": 1,
                "overview": "Mario is super in a whole new way! Combining the finest 3-D graphics ever developed for a video game and an explosive sound track, Super Mario 64 becomes a new standard for video games. It's packed with bruising battles, daunting obstacle courses and underwater adventures. Retrieve the Power Stars from their hidden locations and confront your arch nemesis - Bowser, King of the Koopas!",
                "last_updated": "2020-07-09 20:19:39",
                "rating": "E - Everyone",
                "coop": "No",
                "youtube": "cx78guiPMP8",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    6043
                ],
                "genres": [
                    1,
                    2,
                    15
                ],
                "publishers": [
                    3
                ],
                "alternates": null
            },
         
            
            {
                "id": 239,
                "game_title": "A Bug's Life",
                "release_date": "1998-11-06",
                "platform": 3,
                "players": 1,
                "overview": "As hopeful hero Flik, you're the colony's last chance against the seed-grubbing grasshoppers. Run, fly, kick, squish, and slide through 15 challenging levels of 3-D animated gameplay. Outmaneuver 13 types of enemies, including The Bird and her deadly beak. Then, throw your weight around with tough antics like the Berry Attack and the Butt-Bounce. Because on this ride, you'll need more than just high hopes.\r\n\r\n• Search for power-ups, tokens and objects to use in the \"Living World.\"\r\n• Get a bug's-eye-view of a magical 3-D world.\r\n• Swing, fly, slide and navigate Flik through immense bug-infested levels.",
                "last_updated": "2018-08-11 15:01:11",
                "rating": "E - Everyone",
                "coop": "No",
                "youtube": "j0ITQ9h2o4c",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    2383
                ],
                "genres": [
                    2
                ],
                "publishers": [
                    33
                ],
                "alternates": null
            },
            {
                "id": 240,
                "game_title": "Army Men: Sarge's Heroes",
                "release_date": "2000-11-16",
                "platform": 3,
                "players": 4,
                "overview": "CONFIDENTIAL. 0600 hours: Tan forces captured Bravo Company Commandos. General Plastro has new weapons of mass destruction: magnifying glass, M-80 firecrackers and the garbage disposal. This is a job for Sarge. Requisition M-60s, shotguns, bazookas, flame throwers, grenades, sniper rifles, mortars, mine sweepers and plenty of ammo. Good luck, soldier.",
                "last_updated": "2020-02-17 06:17:04",
                "rating": "T - Teen",
                "coop": "No",
                "youtube": "V5IbVO1MUbc",
                "os": null,
                "processor": null,
                "ram": null,
                "hdd": null,
                "video": null,
                "sound": null,
                "developers": [
                    77
                ],
                "genres": [
                    1,
                    8
                ],
                "publishers": [
                    63
                ],
                "alternates": null
            }
        ]
    },
    "include": {
        "boxart": {
            "base_url": {
                "original": "https://cdn.thegamesdb.net/images/original/",
                "small": "https://cdn.thegamesdb.net/images/small/",
                "thumb": "https://cdn.thegamesdb.net/images/thumb/",
                "cropped_center_thumb": "https://cdn.thegamesdb.net/images/cropped_center_thumb/",
                "medium": "https://cdn.thegamesdb.net/images/medium/",
                "large": "https://cdn.thegamesdb.net/images/large/"
            },
            "data": {
                "4": [
                    {
                        "id": 846,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/4-1.jpg",
                        "resolution": "1000x705"
                    },
                    {
                        "id": 847,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/4-1.jpg",
                        "resolution": "1000x705"
                    }
                ],
                "42": [
                    {
                        "id": 581,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/42-1.jpg",
                        "resolution": "1000x693"
                    },
                    {
                        "id": 215518,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/42-1.jpg",
                        "resolution": null
                    }
                ],
                "68": [
                    {
                        "id": 864,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/68-1.jpg",
                        "resolution": "1000x691"
                    },
                    {
                        "id": 865,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/68-1.jpg",
                        "resolution": "1000x694"
                    }
                ],
                "141": [
                    {
                        "id": 7164,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/141-1.jpg",
                        "resolution": "2100x1532"
                    },
                    {
                        "id": 7165,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/141-1.jpg",
                        "resolution": "2100x1532"
                    }
                ],
                "160": [
                    {
                        "id": 28559,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/160-1.jpg",
                        "resolution": "1000x688"
                    },
                    {
                        "id": 28560,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/160-1.jpg",
                        "resolution": "1000x694"
                    }
                ],
                "161": [
                    {
                        "id": 894,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/161-1.jpg",
                        "resolution": "1000x697"
                    },
                    {
                        "id": 83199,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/161-1.jpg",
                        "resolution": "1050x768"
                    }
                ],
                "162": [
                    {
                        "id": 517,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/162-1.jpg",
                        "resolution": "1000x686"
                    },
                    {
                        "id": 111271,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/162-1.jpg",
                        "resolution": "2100x1536"
                    }
                ],
                "173": [
                    {
                        "id": 7353,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/173-1.jpg",
                        "resolution": "2100x1532"
                    },
                    {
                        "id": 7354,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/173-1.jpg",
                        "resolution": "2100x1532"
                    }
                ],
                "175": [
                    {
                        "id": 7469,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/175-1.jpg",
                        "resolution": "2100x1532"
                    },
                    {
                        "id": 7470,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/175-1.jpg",
                        "resolution": "2100x1532"
                    }
                ],
                "176": [
                    {
                        "id": 2445,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/176-1.jpg",
                        "resolution": "2100x1539"
                    },
                    {
                        "id": 2446,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/176-1.jpg",
                        "resolution": "2100x1533"
                    }
                ],
                "178": [
                    {
                        "id": 540,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/178-1.jpg",
                        "resolution": "1000x690"
                    },
                    {
                        "id": 541,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/178-1.jpg",
                        "resolution": "2107x1473"
                    }
                ],
                "216": [
                    {
                        "id": 234524,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/216-1.jpg",
                        "resolution": null
                    },
                    {
                        "id": 235403,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/216-1.jpg",
                        "resolution": null
                    }
                ],
                "228": [
                    {
                        "id": 2429,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/228-1.jpg",
                        "resolution": "2100x1540"
                    },
                    {
                        "id": 2430,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/228-1.jpg",
                        "resolution": "2100x1536"
                    }
                ],
                "229": [
                    {
                        "id": 2431,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/229-1.jpg",
                        "resolution": "2100x1524"
                    },
                    {
                        "id": 2432,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/229-1.jpg",
                        "resolution": "2100x1540"
                    }
                ],
                "230": [
                    {
                        "id": 538,
                        "type": "boxart",
                        "side": "front",
                        "filename": "boxart/front/230-1.jpg",
                        "resolution": "1000x682"
                    },
                    {
                        "id": 539,
                        "type": "boxart",
                        "side": "back",
                        "filename": "boxart/back/230-1.jpg",
                        "resolution": "1000x687"
                    }
                ]
               
            }
        },
        "platform": {
            "data": {
                "3": {
                    "id": 3,
                    "name": "Nintendo 64",
                    "alias": "nintendo-64"
                }
            }
        }
    },
    "pages": {
        "previous": null,
        "current": "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=8b574d53e9ff612a214486cfe8def1f5c045b0e4eaac50cfd54aa7873d89fd7b&id=3&fields=players%2Cpublishers%2Cgenres%2Coverview%2Clast_updated%2Crating%2Cplatform%2Ccoop%2Cyoutube%2Cos%2Cprocessor%2Cram%2Chdd%2Cvideo%2Csound%2Calternates&include=boxart%2Cplatform&page=1",
        "next": "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=8b574d53e9ff612a214486cfe8def1f5c045b0e4eaac50cfd54aa7873d89fd7b&id=3&fields=players%2Cpublishers%2Cgenres%2Coverview%2Clast_updated%2Crating%2Cplatform%2Ccoop%2Cyoutube%2Cos%2Cprocessor%2Cram%2Chdd%2Cvideo%2Csound%2Calternates&include=boxart%2Cplatform&page=2"
    },
    "remaining_monthly_allowance": 2895,
    "extra_allowance": 0,
    "allowance_refresh_timer": 1014265
}

标签: iosswiftuitableview

解决方案


我不清楚你的问题,尤其是关于i just scrolled past become a single image and stick我这里有几个问题:

您是否尝试在此 tableview 方法中附加图像?

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

UITableViewCell 
{

}

为什么您要尝试从单元格中保存 imageview 的引用

self.coverImage = cell.tableViewCoverImage.image!

您尝试附加图像的代码在哪里?


推荐阅读