【问题标题】:How to hide / unhide section in Collection View如何在收藏视图中隐藏/取消隐藏部分
【发布时间】:2016-07-14 09:30:51
【问题描述】:

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

一个

B

C

然后我想隐藏B部分,那么它会是这样的:

一个

C

我试过了

collectionView.deleteSections(NSIndexSet(index: 1))

但它崩溃并说:

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

【问题讨论】:

  • 您应该通过调用reloadData 从数据源中删除部分并重新加载集合视图。这将触发func numberOfSectionsInCollectionView(_ collectionView: UICollectionView) -> Int,您将在其中返回更新的部分数量。
  • 因为我想重用它,我只想隐藏/取消隐藏部分,所以删除数据部分在我的情况下并不好。
  • 如果您确实想像@fiks 所说的那样删除数据源,请尝试将部分大小设为零?

标签: ios swift collectionview


【解决方案1】:

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

我写了一些代码,用它作为理解概念的起点:

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
}

【讨论】:

  • 我想我需要有 2 个数组。一个原始数组和一个用于操作的数组。
  • 最适合您的。问题是,您有两件事要更新:1)视图模型,因此告诉集合视图添加/删除部分/单元格和 2)用于塑造集合视图的数据模型。这两件事必须是一致的,所以如果你要求删除一个部分,你的 dataSource 方法也应该少返回一个部分。
【解决方案2】:

我用 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 包含节中的项目数

当你需要在方法中隐藏 pass 部分时

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

希望对你有帮助.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2012-12-15
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多