CollectionView上的reloadData,Swift

问题描述 投票:-1回答:1
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UsersCollectionViewCell


    someRequest(username: self.usernameUrl) { (userInfo, error) in
            guard let userInfo = userInfo else {
                // present error
                return
            }
            print("Running")

            let user_image_url = userInfo.items.map{($0.avatarURL)}
            cell.userCellLabel.text = user_name[indexPath.item]                   
    }     
    return cell
}

为什么当我在viewDidAppear上调用reloadData时,someRequest(...)中的代码未运行?

 override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.collectionViewUsers.reloadData()
}

P.s。 Somerequest只需执行Alamofire获取

swift xcode uicollectionview uicollectionviewcell
1个回答
0
投票

异步Alamofire请求必须在cellForItemAt处理程序之外。因为每次单元格出现在屏幕上都会调用cellForItemAt,这意味着它会在滚动时尝试多次为同一单元格获取相同的数据,这是不希望的。因此,viewDidLoad是开始获取的好地方,异步调用完成后,别忘了重新加载collectionview。

var user_image_url: String?
override func viewDidLoad(_ animated: Bool) {
    someRequest(username: self.usernameUrl) { (userInfo, error) in
        guard let userInfo = userInfo else {
            // present error
            return
        }
        print("Running")

        user_image_url = userInfo.items.map{($0.avatarURL)}
        self.collectionViewUsers.reloadData()
    }
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UsersCollectionViewCell
    if let user_image_url = user_image_url {
        //user_image_url is avaliable
    }
    return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.