首页 文章

单个UIView Scrolling上的多个UICollection视图在从API加载单元数据时不起作用

提问于
浏览
0

enter image description here

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

override 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 function

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

    一些非常基本的提示:

    a)考虑到你正在处理多个线程..所以添加到数组必须非常小心 .

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

相关问题