@pocteg

IOS приложении при загрузке картинок в UICollectionView они начинают прыгать из столбца в столбец. Как исправить баг?

Добрый день

Я загружаю данные из parse.com в UICollectionView. текстовые данные отображаются хорошо. но картинки прыгают из ячейки в ячейку.

Вот видео бага: https://www.youtube.com/watch?v=9XhFj0br1DE&featur...

CatalogViewController.swift

class CatalogViewController: UIViewController, UICollectionViewDataSource, DataProviderProtocol, UICollectionViewDelegate {

@IBOutlet weak var collectionView: UICollectionView!

var isLoad = false
var loadImageCounter: Int = 0

let cellPerPage = 10
var itemGroupData:ItemGroupDataProvider!

override func viewDidLoad() {
    super.viewDidLoad()

    // Set provider
    itemGroupData = ItemGroupDataProvider()
    itemGroupData.delegate = self
    itemGroupData.loadData(objectCount: cellPerPage)

    // First load
    self.isLoad = true
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemGroupData.countObjects();
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    var cell: ItemCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemViewCell", forIndexPath: indexPath) as ItemCollectionViewCell;

    let itmGrp:ItemGroupModel = itemGroupData.objectAtIndex(indexPath.row)

    cell.titleLable.text = itmGrp.title
    cell.itemGroupModel = itmGrp

    if( itmGrp.icon != nil){

        cell.imagePFFile = itmGrp.icon

        itmGrp.icon!.getDataInBackgroundWithBlock { (data, error) -> Void in
            if error == nil && data != nil && data.length > 0 {
                cell.smallImageView.image =  UIImage(data:data!)
            }
        }

    }

    return cell;
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let cell: ItemCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemViewCell", forIndexPath: indexPath) as ItemCollectionViewCell;

}

func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    if isLoad == true || loadImageCounter > 0 {
        return
    }
    if indexPath.item + 1 == itemGroupData.countObjects() && isLoad == false{
        isLoad = true
        itemGroupData.fetchNext(objectCount: cellPerPage)
    }
}


func didLoadData(dataProvider:ItemGroupDataProvider) {

    //self.tableView.reloadData()

    self.collectionView.reloadData();
    self.isLoad = false
}


ItemGroupDataProvider.swift

private let defaultObjectCountLimit = 10

private let maximumTotalCount = 1000

protocol DataProviderProtocol : class{
func didLoadData(dataProvider:ItemGroupDataProvider)


class ItemGroupDataProvider {

private var itemGroupSerivice:ItemGroupService = ItemGroupService()

weak var delegate:DataProviderProtocol?

private var result:[ItemGroupModel] = [ItemGroupModel]()

private(set) var totalCount:Int = 0

private(set) var allItems:Int = 0

func countObjects() -> Int {
    return result.count
}

func objectAtIndex(index:Int) -> ItemGroupModel {
    assert(index > -1 , "Index out of bounds")
    assert(index < result.count, "Index out of bounds")

    return result[index]

}

init(){

}

/**
First load data
*/
func loadData(objectCount limit:Int = defaultObjectCountLimit){
    totalCount = maximumTotalCount

    self.fetchFromService(limit, skip: result.count)
}

/**
Next page load

:param: limit Limit the number of objects for query
*/
func fetchNext(objectCount limit:Int = defaultObjectCountLimit) {
    self.fetchFromService(limit, skip: result.count)
}

/**
Load from server. Parameters limit and skip provide pagination and дщсфешщт

:param: limit Limit the number of objects for query
:param: skip  Skip objects
*/
private func fetchFromService(limit:Int, skip:Int){

    self.itemGroupSerivice.searchItemGroups(limit, skip: skip) {
        (objects,error) in

        if error == nil {
            if objects != nil && objects!.count > 0 {
                self.result.extend(objects!)
            } else{
                self.totalCount = self.result.count
            }

        } else {
            //TODO: error handle
        }
        self.delegate?.didLoadData(self)
    }

}
  • Вопрос задан
  • 636 просмотров
Решения вопроса 1
DaskOFF
@DaskOFF
iOS Developer
Ячейки повторно используются. В методе делегата collectionView
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

Ты устанавливаешь картинку, только если она есть, в противном случае ты не удаляешь старую
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы