如何在集合视图中隐藏/取消隐藏部分

时间:2016-07-14 09:30:52

标签: ios swift collectionview

我有一个集合视图,这个集合视图有3个部分:

A

C

然后我想隐藏B部分,然后看起来像:

A

C

我试过了

collectionView.deleteSections(NSIndexSet(index: 1))

但它崩溃并说:

  

由于未捕获的异常而终止应用   ' NSInternalInconsistencyException',原因:'无效更新:无效   部分数量。包含的部分数量   更新后的集合视图(3)必须等于数量   更新前的集合视图中包含的部分(3),加上   或减去插入或删除的部分数量(0插入,1   删除)'

2 个答案:

答案 0 :(得分:3)

如果您要求集合视图更新自己添加/删除部分或单元格,您还必须更新您的委托方法以返回正确的数字。

我会动态编写一些代码,将其作为理解概念的起点:

var sections = 3
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return sections
}

func removeSectionOne() {
   sections = 2
   collectionView.deleteSections(NSIndexSet(index: 1))
   // At this point the collection view will ask again for the number of sections and it will be updated
}

答案 1 :(得分:1)

我用tableview做了同样的事情,

第一

   BOOL sectionIsOpen[2]; // Your Sections number (3 in your case )

   - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView       {
       return self.arrMenu.count;
    }

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return ((sectionIsOpen[section]) ? [self   numberOfRowsInSection:section] : 0);
      }

[self numberOfRowsInSection:section包含

部分中的项目数

当你需要隐藏方法和

中的传递部分时
   for (NSInteger row = 0; row < [self numberOfRowsInSection:section]; row ++) {
        [indxPths addObject: [NSIndexPath indexPathForRow:row inSection:section]
         ];
    }
    [self.tblMenu beginUpdates];
    if (open) {
        [self.tblMenu insertRowsAtIndexPaths:indxPths withRowAnimation:UITableViewRowAnimationFade];
    }else{
        [self.tblMenu deleteRowsAtIndexPaths:indxPths withRowAnimation:UITableViewRowAnimationFade];

    }
    sectionIsOpen[section] = open;
    [self.tblMenu endUpdates];

希望它有所帮助.....