我想創建類似Facebook NewsFeed的東西,其中,我使用自定義UICollectionViewCell顯示來自JSON的數據(文本/圖像)。我有2個不同的API。一個用於文本,另一個用於圖像(每個單元格都沒有圖像)。重新加載UICollectionViewCell它有圖像
所以,首先,我從我的textAPI中獲取所有文本值,並重新加載myCollectionView。這是完美的。
現在的形象,我使用ImageFetcher獲取圖像,
func ImageFetcher(postId : NSNumber, completion : ((_ image: UIImage?) -> Void)!) {
var image = UIImage()
let urlString = "http://myImageAPI/Image/\(postId)"
let jsonUrlString = URL(string: urlString)
print(urlString)
URLSession.shared.dataTask(with: jsonUrlString!) { (data, response, error) in
do {
if let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any] {
if let images = jsonData["Image"] as? String {
if images == "" {
print("No Image")
} else {
let dataDecoded : Data? = Data(base64Encoded: images, options: .ignoreUnknownCharacters)
image = UIImage(data: dataDecoded!)!
completion(image)
}
}
}
else {
completion(nil)
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
要到單元格中顯示圖像,
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Displaying other elements with text
DispatchQueue.main.async {
self.ImageFetcher(postId: self.myArray[indexPath.item].id!, completion: { (image) -> Void in
customCell.mainImage.image = image
})
// Declared "indexPaths" var indexPaths = [IndexPath]()
// Added this lines
// let indexPath = IndexPath(item: indexPath.item, section: 0)
// self.indexPaths.append(indexPath)
}
return customCell
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.jsonParsing()
}
func jsonParsing() {
//Fetching text data from textAPI
//DispatchQueue.main.async {
// self.collectionView.reloadItems(at: self.indexPaths)
//}
}
代碼工作沒有任何錯誤,但問題是圖片只有當我點擊它們時纔會出現。 (我可以在單元格中看到空的/白色的imageView,直到我點擊它。只要我點擊imageView圖像出現),我感覺它的東西與DispatchQueue.main.async,但不知道。
我不想在獲取圖像後重新加載整個collectionView。只是想重新加載那些有Image的單元。我在許多解決方案上找到了 collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
,但不知道如何在這種情況下使其工作。任何人都可以在這裏幫我嗎?任何幫助都感激不盡。
[從這裏開始引用。](https://stackoverflow.com/questions/28206492/refresh-certain-row-of-uitableview-based-on-int-in-swift )如果你仍然需要幫助,你可以問。 –
謝謝!讓我試試看。 – iUser
你可以稍微解釋一下 - > **問題是圖片只有當我點擊它們時纔會出現** –