无法更改UICollectionView上的backgroundView属性

Sim*_*onB 8 ios uicollectionview

我有一个UICollectionView,我正在尝试使用backgroundView属性设置背景图像,如果CollectionView中有任何数据.我有导航将更改数据,并重新加载集合视图(调用[self.collectionView reloadData]).出于某种原因,我得到了非常奇怪的结果.首先,有时当我设置属性时,它会出现在collectionView单元格的顶部并遮挡它们.其次,当我尝试更改属性时,它不会在屏幕上更改.这让我疯了!实施起来似乎很简单!

所以在Code中.在viewDidLoadUICollectionViewController

- (void)viewDidLoad {
[self loadSections];
[self setupBackgroundView;
}
Run Code Online (Sandbox Code Playgroud)

Load sections方法只是加载我用于集合视图的数据,然后它还调用一个方法来设置背景视图,根据是否有如下数据来决定要添加的视图:

- (void)loadSections {
[self loadPictures];
[self setupBackgroundImage];
}

- (void)setupBackgroundImage {
if ([self.sections count] == 0 || !self.sections) {
    self.collectionView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"TakePhoto"]];
}
else {
    self.collectionView.backgroundView = nil;
}
}
Run Code Online (Sandbox Code Playgroud)

现在,当视图首次加载时,如果没有数据,那么没有单元格显示背景图像正确显示.然后我更改数据,现在我要显示一些单元格,调用setupBackgroundImage,我可以验证backgroundImage属性是否设置为nil(我甚至在此处进行了断点检查并检查了值,它是nil).但背景图像仍然可见.

此外,如果我将nil更改为另一个图像,则不会显示此新图像.

而且更奇怪.如果我显示了一些单元格并设置了背景图像,则此图像会整齐地显示在单元格后面.如果我然后使用新数据集重新加载数据,则图像将显示在单元格前面,使其模糊.我不知道这是怎么发生的,因为后台视图应该落后于所有其他人.

有谁知道为什么会这样.是否在任何地方缓存?或者我只是做些傻事?我在这里完全失去了 - 花了更多的时间在这上面而不是编写它使用的自定义布局!

Sim*_*onB 0

好吧,我找到了解决我的具体问题的方法,虽然我仍然不明白为什么我会遇到问题中提到的奇怪行为,至少这种方式允许我更改背景图像。

基本上我创建一个属性来保存 a UIImageView,然后将其设置UICollectionView为该属性。然后我可以通过我保存的属性更改图像视图中的图像。

- (void)viewDidLoad {
    [self loadSections];
    self.backgroundImageView = [[UIImageView alloc] initWithImage:nil];
    self.backgroundImageView.contentMode = UIViewContentModeCenter;
    self.collectionView.backgroundView = self.backgroundImageView;
}

- (void)setupBackgroundImage {
    if ([self.sections count] == 0 || !self.sections) {
        self.backgroundImageView.image = [UIImage imageNamed:@"TakePhoto"];
    }
    else {
            self.backgroundImageView.image = nil;
    }
}

- (void)loadSections {
    [self loadPictures];
    [self setupBackgroundImage];
}
Run Code Online (Sandbox Code Playgroud)

self.backgroundImageView我为了保留对背景视图的引用而定义的属性在哪里。

如果有人对问题中提到的奇怪行为有任何见解,我真的很想听听!