收集视图单元格刷新不会发生
加载视图时,我从api调用填充数据并将其显示到单元格中:
override func viewDidLoad() { super.viewDidLoad() parseData(urll: url) }
当我使用search栏进行search时,我正在使用以下代码填充一组新的项目:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { let keywords = searchBar.text let finalKey = keywords?.replacingOccurrences(of: " ", with: "+") let finalurl = "https://api.giphy.com/v1/gifs/search?api_key=0d4f9877de6d4927943adf5a0d20e8a0&q=\(finalKey!)&limit=25&offset=0&rating=G&lang=en" parseData(urll: finalurl) self.view.endEditing(true) }
但是,当它加载新的项目旧的项目不会被删除,我试过使用重新加载数据,但没有奏效。
而且我已经重载了parseData()
函数中的数据函数。
parsedata()
代码:
func parseData(urll : String) { var request = URLRequest(url: URL(string: urll)!) request.httpMethod = "GET" let config = URLSessionConfiguration.default let session = URLSession(configuration: config, delegate: nil, delegateQueue: .main) let task = session.dataTask(with: request) { (data, response, error) in if error != nil { print(error!) } else { do { let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary if let gifArray = fetchedData.value(forKey: "data") as? NSArray { if let gifarrayImg = gifArray.value(forKey: "images") as? NSArray { if let gifarrayImgFixedWdth = gifarrayImg.value(forKey: "fixed_width") as? NSArray { for gif in gifarrayImgFixedWdth { if let gifDict = gif as? NSDictionary { if let imgURL = gifDict.value(forKey: "url") { print(imgURL) self.imgUrlArray.append(imgURL as! String) } if let imgHeight = gifDict.value(forKey: "height") { self.height.append(imgHeight as! String) print(imgHeight) } DispatchQueue.main.async { self.collectionView.reloadData() } } } } } } } catch { print("Error2") } } } task.resume() }
CollectviewdataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgUrlArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CollectionViewCell cell?.layer.shouldRasterize = true cell?.layer.rasterizationScale = UIScreen.main.scale let resource = ImageResource(downloadURL: URL(string : imgUrlArray[indexPath.row])!, cacheKey: imgUrlArray[indexPath.row]) cell?.imgview.kf.setImage(with: resource) return cell! }
旧项目不会被删除,因为您将search的图像URL附加到现有的imageUrlArray属性。 因此,您可以在进行search请求之前删除该数组中的所有项目。 只需将此行添加到parsedata()
函数的顶部parsedata()
:
self.imageUrlArray.removeAll(keepingCapacity: false)