문제

UICollectionView 내가 하려고를 삽입하는 품목이 그것으로 동적으로/애니메이션.그래서 일부는 기능을 다운로드 이미지를 비동기적으로 삽입하려는 항목에서 배치합니다.

면 나는 데이터가 다음을 수행:

[self.collectionView performBatchUpdates:^{
    for (UIImage *image in images) {
        [self.collectionView insertItemsAtIndexPaths:****]
    }
} completion:nil];

지금 장소에서의 ***, 에,나는 통과해야의 배열 NSIndexPaths, 해야 하는 시점의 위치를 새로운 항목을 삽입 할 수 있습니다.내가 매우 혼란 때문에 제공한 후 이 위치,어떻게 제공하는 실제 이미지가 표시되어야에서는 위치에 있습니까?

감사


업데이트:

resultsSize 포함하는 데이터의 크기 소스 배열, self.results, 하기 전에 새로운 데이터 추가 데이터에서 newImages.

[self.collectionView performBatchUpdates:^{

    int resultsSize = [self.results count];
    [self.results addObjectsFromArray:newImages];
    NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

    for (int i = resultsSize; i < resultsSize + newImages.count; i++)
          [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];

          [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];

} completion:nil];
도움이 되었습니까?

해결책

삽입,삭제,이동하는 섹션과목 에서"컬렉션 보기 프로그래밍 가이드 iOS":

를 삽입,삭제,이동 또는 하나의 섹션 또는 항목을 따라야 합니다 이 단계:

  1. 업데이트 데이터에서 당신의 데이터 원본 개체입니다.
  2. 전화 적절한 방법을의 컬렉션을 볼 수를 삽입 또는 삭제된 섹션 또는 항목입니다.

하는 것이 중요 데이터를 업데이트 소스기 전에 통보 컬렉션 뷰의 모든 변경합니다.컬렉션 보정 방법 는 데이터 소스에 포함되는 현재 정확한 데이터이다.않는 경우 지,컬렉션 보기 나타날 수 있습니다 잘못된 설정 항목에서 데이터 원본 또는 요구되지 않은 항목이 충돌하기 app.

그래서 당신의 경우,추가해야 합니다 이미지 컬렉션 데이터 보기 소스에 먼저 전화 insertItemsAtIndexPaths.컬렉션을 보이는 데이터 소스를 위임하는 기능을 제공하기 위해 삽입되는 항목입니다.

다른 팁

나는 그냥 구현되는 것으로 신속합니다.그래서 공유하고 싶은 나의 구현합니다.먼저 초기화의 배열을 NSBlockOperations:

    var blockOperations: [NSBlockOperation] = []

컨트롤러 변경됩니다,다시 init 배열:

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    blockOperations.removeAll(keepCapacity: false)
}

에서 변경 않았 개체방법:

    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

    if type == NSFetchedResultsChangeType.Insert {
        println("Insert Object: \(newIndexPath)")

        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.insertItemsAtIndexPaths([newIndexPath!])
                }
            })
        )
    }
    else if type == NSFetchedResultsChangeType.Update {
        println("Update Object: \(indexPath)")
        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.reloadItemsAtIndexPaths([indexPath!])
                }
            })
        )
    }
    else if type == NSFetchedResultsChangeType.Move {
        println("Move Object: \(indexPath)")

        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.moveItemAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
                }
            })
        )
    }
    else if type == NSFetchedResultsChangeType.Delete {
        println("Delete Object: \(indexPath)")

        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.deleteItemsAtIndexPaths([indexPath!])
                }
            })
        )
    }
}

에서 변경 않았 섹션은 방법:

func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {

    if type == NSFetchedResultsChangeType.Insert {
        println("Insert Section: \(sectionIndex)")

        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.insertSections(NSIndexSet(index: sectionIndex))
                }
            })
        )
    }
    else if type == NSFetchedResultsChangeType.Update {
        println("Update Section: \(sectionIndex)")
        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.reloadSections(NSIndexSet(index: sectionIndex))
                }
            })
        )
    }
    else if type == NSFetchedResultsChangeType.Delete {
        println("Delete Section: \(sectionIndex)")

        blockOperations.append(
            NSBlockOperation(block: { [weak self] in
                if let this = self {
                    this.collectionView!.deleteSections(NSIndexSet(index: sectionIndex))
                }
            })
        )
    }
}

그리고 마지막으로,았 컨트롤러았다 내용을 변경 방법:

func controllerDidChangeContent(controller: NSFetchedResultsController) {        
    collectionView!.performBatchUpdates({ () -> Void in
        for operation: NSBlockOperation in self.blockOperations {
            operation.start()
        }
    }, completion: { (finished) -> Void in
        self.blockOperations.removeAll(keepCapacity: false)
    })
}

나 개인적으로 추가 코드에 deinit 방법뿐만 아니라,하기 위해서 작업을 취소할 때 ViewController 는 할당 해제:

deinit {
    // Cancel all block operations when VC deallocates
    for operation: NSBlockOperation in blockOperations {
        operation.cancel()
    }

    blockOperations.removeAll(keepCapacity: false)
}

를 직면하고 있었는 유사한 문제를 삭제하는 동안 품목에서는 인덱스와 이는 내 생각이 우리가 할 필요가 사용하는 동안 performBatchUpdates: 방법입니다.

1#첫 번째 호출 deleteItemAtIndexPath 항목을 삭제 하에서 컬렉션 보기입니다.

2#삭제를 요소에서 배열입니다.

3#업데이트 컬렉션을 보기를 새로 고침하여 데이터입니다.

[self.collectionView performBatchUpdates:^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
            [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
            [self.addNewDocumentArray removeObjectAtIndex:sender.tag];
        } completion:^(BOOL finished) {
            [self.collectionView reloadData];
        }];

이를 제거하는 모든 충돌고 주장 실패입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top