ios - 访问位于设备屏幕中心的 UICollectionView 单元格中的 View

标签 ios objective-c uiscrollview uicollectionview uicollectionviewcell

如果滚动发生后单元格位于设备屏幕的中心,我正在尝试更改 Collection View 单元格内 View 的背景颜色。我目前有一种工作方法,可以在滚动后更改所有当前可见单元格内 View 的背景颜色,如下所示:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{


    if(scrollView==_collectionViewFollwersFeed)
    {
        for (UICollectionViewCell *cell in [self.collectionViewFollwersFeed visibleCells]) {

            UIView *tsView;

            tsView=(UIView *)[cell viewWithTag:99];

            tsView.backgroundColor = [UIColor redColor];

        }
    }
}

当我尝试编辑此方法以仅更改位于中间的单元格内的 View 的背景颜色时,我无法使此功能正常工作。这是我认为应该有效的调整:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{


    if(scrollView==_collectionViewFollwersFeed)
    {

        NSIndexPath *centerCellIndexPath =
        [self.collectionViewFollwersFeed indexPathForItemAtPoint:
         [self.view convertPoint:[self.view center] toView:self.collectionViewFollwersFeed]];

        UICollectionViewCell *cell;
        NSString *CellIdentifier;

        CellIdentifier = @"FollowersFeed";
        cell = [_collectionViewFollwersFeed dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:centerCellIndexPath];

        UIView *tsView = (UIView *)[cell viewWithTag:99];

        tsView.backgroundColor = [UIColor redColor];

    }
}

有谁知道为什么此方法不会更改屏幕中心单元格的 View 背景颜色?

最佳答案

问题是这一行:

cell = [_collectionViewFollwersFeed dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:centerCellIndexPath];

这会创建一个新单元格,该单元格不是您的 Collection View 当前显示的单元格。

要访问 Collection View 中已有的单元格,请使用:

cell = [_collectionViewFollwersFeed cellForItemAtIndexPath:centerCellIndexPath];

关于ios - 访问位于设备屏幕中心的 UICollectionView 单元格中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452810/

相关文章:

iphone - 标签未显示在叠加 UIView 中

ios - 只有 UIButton 的中心是可点击的

objective-c - 为什么我的导航栏 Controller 不处理我的导航栏 View 上的 touchesEnded 事件?

ios - VoiceLayer iOS obj c

objective-c - ARC - 带有 CF 实例变量的 ObjC 对象

ios - 当选择 ScrollView subview 时在 subview 位置滚动

ios - 关闭 UIScrollView 中的键盘

ios - 放弃文本字段 - 代码重用

iphone - 将卫星 View 添加到具有 3D 功能的 MKMapKit IOS 6

ios - indexPath.row 在 tableView 自定义单元格 iOS 中没有给出正确的值