確定更新一個UICollectionView,我真的卡住位置:/在蘋果的集合視圖編程指南插入它說,一個項目有兩個步驟:,當一個項目被添加(核心數據),停留在insertItemsAtIndexPaths
- 更新數據源對象中的數據。
- 調用收集視圖的相應方法來插入或刪除節或項目。
我被困在第二個。我希望新項目出現在集合視圖的開始處。我不知道要爲insertItemsAtIndexPaths:參數放置什麼。我知道它需要一個索引對象數組,但我不知道如何告訴它選擇集合的開始,因爲它是索引值,並且我也很困惑如何告訴它其他的東西。你可以在我之前的代碼中看到(cellForItemAtIndexPath)我在填充集合時修改了單元內按鈕元素的屬性。如果我想在創建時修改新項目,我該怎麼做?我非常感謝這方面的任何幫助,我覺得我在這裏錯過了很多,而且真的碰到了一堵磚牆。
@implementation RepsCollectionViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Error : %@", error);
abort();
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Collection view data source
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> secInfo = [self.fetchedResultsController.sections objectAtIndex:section];
return [secInfo numberOfObjects];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
RepCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
Rep *rep = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.repButton.pressed = [rep.completed boolValue];
cell.repButton.indexPath = indexPath;
return cell;
}
#pragma mark - Fetched Results Controller
-(NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Rep" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"dateTimeCreated" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
_fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
#pragma mark - IBActions
- (IBAction)addRep:(id)sender {
[NSEntityDescription insertNewObjectForEntityForName:@"Rep" inManagedObjectContext:self.managedObjectContext];
[self.collectionView performBatchUpdates:^{
[self.collectionView insertItemsAtIndexPaths:WHAT TO PUT HERE?];
} completion:nil];
}
例如,如果添加了多個對象,則會導致崩潰。 – 2014-09-13 11:17:20
冷靜,非常感謝你花時間給出這樣一個詳細的答案。我試過了 - 只是爲了NSFetchedResultsChangeInsert選項 - 它的功能就像一個魅力!我將在週末後添加所有委託方法的其餘要求,並將在未來使用此方法更新集合視圖。不夠感謝你! – Jared 2014-09-13 13:34:28