从API加载单元格数据时,单个UIView上的多个UICollection View滚动不起作用

时间:2018-08-16 09:55:34

标签: ios uicollectionview swift4 uicollectionviewcell

enter image description here

在主屏幕部分中,我有三个不同的UICollection视图,其中两个(热门新闻和住宿)从API获取数据,最后一个(类别)具有静态数据,问题是从API加载数据时我无法滚动UICollection视图单元格的静态部分,但随着数据加载完成,一切正常,我无法找到问题的解决方案,请帮帮我

覆盖func viewDidLoad(){         super.viewDidLoad()

       topNewCV.delegate = self
        topNewCV.dataSource = self

        accommodationCV.delegate = self
        accommodationCV.dataSource = self

        categoryCV.dataSource = self
        categoryCV.delegate = self

  //Loading getNearByPlace function
        self.getNearByPlace()  
}

// cellForItemAt indexPath函数

func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell {

    if collectionView == accommodationCV {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AccommodationCollectionViewCell", for: indexPath) as! AccommodationCollectionViewCell
                cell.titleContainer.text = self.accommodationObject.titleArray[indexPath.row]

        if self.accommodationObject.titleArray.count == self.accommodationObject.imgArray.count {
        if let img = cache.object(forKey: self.accommodationObject.imgArray[indexPath.row] as AnyObject) {
            DispatchQueue.global().async {
                DispatchQueue.main.async {
                    cell.imgContainer.image = img as? UIImage
                }
            }
        } else {
            DispatchQueue.global().async {
                DispatchQueue.main.sync {
                    cell.imgContainer.image = UIImage(url: URL(string: "\(self.accommodationObject.imgArray[indexPath.row])"))
                    self.cache.setObject(UIImage(url: URL(string: "\(self.accommodationObject.imgArray[indexPath.row])"))!, forKey: self.accommodationObject.imgArray[indexPath.row] as AnyObject)
                }
            }
        }
        } else {
            print("Both have not equal data")
        }

        return cell
    } else if collectionView == categoryCV {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionViewCell", for: indexPath) as! CategoryCollectionViewCell

                cell.categorymodel = self.categoryModels?[indexPath.item]

        if indexPath.row % 2 == 0 {
            cell.categoryCVViewContainer.backgroundColor =  colorLiteral(red: 0.3333333333, green: 0.7844525506, blue: 0.6620362924, alpha: 1)
        } else {
             cell.categoryCVViewContainer.backgroundColor =  colorLiteral(red: 1, green: 0.4039215686, blue: 0.4039215686, alpha: 1)
        }
        return cell
    }
    return cell
}

//这个乐趣是从api获取数据

func getNearByPlace(){

    var strGoogleApi = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(user_latitude!), \(user_longitude!)&radius=1000&keyword=hotel&sensor=true&key=abc”
    strGoogleApi = strGoogleApi.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    print(strGoogleApi)
    var urlRequest = URLRequest(url: URL(string: strGoogleApi)!)
    urlRequest.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if error == nil {
            if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]{

                if let allResults = json!["results"] as? [[String: Any]] {
                    print(allResults)

                    for result in allResults {

                        var geometry = [String: Any]()
                        geometry = result["geometry"] as! [String: Any]
                        var location = [String: Any]()
                        location = geometry["location"] as! [String: Double]

                        self.latitudeArray.append(location["lat"] as! Double)
                        self.longitudeArray.append(location["lng"] as! Double)

                        let name = result["name"]
                        var  image = [[String: Any]]()

                        if result["photos"] != nil {
                        image = result["photos"] as! [[String: Any]]
                            var img = image[0]
                            let url = self.getImageFromApi(image: img["photo_reference"] as! String)
                            self.imgReferenceArray.append(url)
                        } else {
                            self.imgReferenceArray.append(self.icons)
                        }

                        let place_id = result["place_id"]
                        let address = result["vicinity"]

                        if result["name"] != nil {
                            self.nameArray.append(name as! String)
                            self.accommodationObject.titleArray = self.nameArray
                        }
                        if result["place_id"] != nil {
                            self.placeIdArray.append(place_id as! String)
                        } else if result["vicinity"] != nil {
                            self.addressArray.append(address as! String)
                        }
                    }
                }
            }
            OperationQueue.main.addOperation({
                if self.nameArray.count != 0 {
                    DispatchQueue.main.async {
                        self.accommodationCV.reloadData()
                        self.categoryCV.reloadData()
                    }
                }
            })
            self.accommodationObject.imgArray = self.imgReferenceArray
        }
    }
    task.resume()
}

1 个答案:

答案 0 :(得分:0)

一些非常基本的提示:

a)考虑到您正在处理多个线程..因此,添加数组时必须格外小心。

b)如果重新加载,则停止先前对“任务” var的调用。例如,将任务保存在实例var中:调用task.cancel()