2016-07-14 125 views
2

我有一个集合视图,这个集合中有3个部分:如何隐藏在集合视图/取消隐藏部分

一个

Ç

然后我想隐藏B部分,那么它将如下所示:

一个

Ç

我已经试过

collectionView.deleteSections(NSIndexSet(index: 1)) 

,但它崩溃并说:

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

+2

您应该从数据源中删除部分,并通过调用'reloadData'重装集合视图。这将触发'func numberOfSectionsInCollectionView(_ collectionView:UICollectionView) - > Int',你将返回更新的节数。 – fiks

+0

因为我想重用它,那么我只想隐藏/取消隐藏部分,所以在我的情况下删除数据部分不会很好。 – Khuong

+0

如果您确实想要删除@fiks所说的数据源,请尝试将部分大小设置为零? – childrenOurFuture

回答

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 
} 
+0

我想我需要有2个数组。一个原始数组和一个操作数组。 – Khuong

+0

什么最适合你。事情是,你有两件事要更新:1)视图模型,告诉集合视图添加/删除部分/单元格和2)用于塑造集合视图的数据模型。这两件事必须是连贯的,所以如果你要求删除一个部分,你的dataSource方法也应该少返回一个部分。 –

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]; 

希望它可以帮助通段.....