1

我創建了一個視圖控制器具有導航欄和UiCollectionView。 UI集合視圖包含自定義UICollectionViewCell。導航欄包含兩個UIBarButton項目,一個在左下角 - 準備從前一頁開始,其他項目在右上角 - 安排刪除UI CollectionView中的單元格,如下圖所示:獲取UICollectionViewCell從indexPath的UIBarButtonItem時被竊聽

Main Screen

現在我想在點擊右下角的UIBarButtonItem時刪除所選的UICollectionViewCell。

這怎麼我cellForItemAtIndexPath方法是這樣的:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{ 
self.GlobalIndexPath = indexPath; 
MessagesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"messagesCell" forIndexPath:indexPath]; 
cell.MessageHeading.text = [self.Message_Heading objectAtIndex:indexPath.row]; 
cell.MessageSubject.text = [self.Message_Subject objectAtIndex:indexPath.row]; 
cell.MessageContent.text = [self.Message_Details objectAtIndex:indexPath.row]; 
[cell.Checkbox setHidden:YES]; 
[cell.Checkbox setChecked:NO]; 
} 

我試圖像聲明Indexpath作爲全局變量和使用它的按鈕事件如下解決方案:

@property (strong,nonatomic) NSIndexPath *GlobalIndexPath; 
some other code ....... 

//When Bin Icon(UIBarButtonItem) Clicked 
- (IBAction)DeleteMessages:(id)sender { 

[self.view makeToast:@"You clicked delete button !"]; 

NSIndexPath *indexPath = [self.MessageCollectionView.indexPathsForVisibleItems objectAtIndex:0] ; 
BOOL created = YES; 
// how to get desired selected cell here to delete 
MessagesCollectionViewCell *cell = [self.MessageCollectionView cellForItemAtIndexPath:self.GlobalIndexPath]; 
if([cell.Checkbox isHidden]) 
{ 
    [cell setHidden:YES]; 
} 
else{ 
    [cell.Checkbox setChecked:NO]; 
    [cell.Checkbox setHidden:YES]; 
} 
} 

它不工作。

用於顯示UICollectionViewCell選作檢查,我使用@克里斯Chris Vasselli's solution

請幫助我。提前致謝。

回答

0

有幾個步驟。首先,確定所選indexPath,但不要以爲有當運行方法的選擇....

// in your button method 
NSArray *selection = [self.MessageCollectionView indexPathsForSelectedItems]; 
if (selection.count) { 
    NSIndexPath *indexPath = selection[0]; 
    [self removeItemAtIndexPath:indexPath]; 
} 

有兩個步驟,從集合視圖中刪除的項目:從數據源中刪除,並告訴它改變了看法。

- (void)removeItemAtIndexPath:(NSIndexPath *)indexPath { 
    // if your arrays are mutable... 
    [self.Message_Heading removeObjectAtIndex:indexPath.row]; 

    // OR, if the arrays are immutable 
    NSMutableArray *tempMsgHeading = [self.Message_Heading mutableCopy]; 
    [tempMsgHeading removeObjectAtIndex:indexPath.row]; 
    self.Message_Heading = tempMsgHeading; 
    // ... 

對每個數據源數組執行上述操作。最後一步是告知該數據源改變了集合視圖,它必須自行更新。有幾種方法可以做到這一點。最簡單的是:

// ... 
    [self.MessageCollectionView reloadData]; 

OR,多了幾分優雅:

[self.MessageCollectionView deleteItemsAtIndexPaths:@[indexPath]]; 
} // end of removeItemAtIndexPath 
+0

謝謝你這麼多@danh –