ios - 在 UICollectionViewCell 的 subview 上调用 removeFromSuperview 在第一次加载时不起作用,仅当单元格被重用时

标签 ios uicollectionview uicollectionviewcell

我有一个包含多个 subview 的 Collection View 单元格。我想完全删除其中一个 subview ,以便相邻的 subview 可以扩展以通过约束填充该空间。

这个约束配置在 Storyboard的原型(prototype)单元中设置, subview 已经在原型(prototype)中,准备在单元实例化后移除。

我的 UICollectionViewCell 子类有一个执行此操作的 setter:

- (void)setThing:(NSString *)aThing
{
     if (!aThing)
     {
          [self.thingContainerView removeFromSuperview];
          return;
     }
     // proceed if aThing exists

当设置单元格时:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mycellid" forIndexPath:indexPath];
    cell.aThing = nil; //this should trigger removal of one of the cell's subviews
    return cell;
}     

问题是UICollectionViewCell 第一次加载时, subview 还没有被删除。 一旦我将单元格滚动到屏幕外并返回到它, subview 已经已按预期删除。所以我假设当我第一次设置属性时单元格没有完全布局存在某种问题。

如何让它发挥作用?

最佳答案

我认为此时 View 尚未布局,因此无法删除 subview 。尝试用不同的方法删除它,例如;

- (void) didMoveToSuperview
{
    if (!self.aThing)
    {
         [self.thingContainerView removeFromSuperview];
    }
}

这将在您的 Collection View 单元格中被覆盖。

可能有更合适的方法来调用它,但这应该可行。

关于ios - 在 UICollectionViewCell 的 subview 上调用 removeFromSuperview 在第一次加载时不起作用,仅当单元格被重用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374514/

相关文章:

ios - 如何使用 RxSwift 观察 UITextField 中的文本变化?

ios - UITableView 防止子类的委托(delegate)方法

ios - UICollectionView - 动态单元格高度?

ios - 可以嵌套可重用的 UICollectionViewCells

ios - 如何在 Swift 中以编程方式更改 UICollectionViewCell 大小?

IOS导航到新 View 但出现黑屏

ios - iOS 上的视频调整大小/裁剪/合并

ios - 滚动后 UICollectionViewCells subview 呈现错误

当标题在屏幕上时,IOS UICollectionView insertItemsAtIndexPaths 崩溃

ios - PHCachingImageManager.requestImage 总是被调用两次?