Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change backgroundView property on UICollectionView

I have a UICollectionView and I am trying to set a background image using the backgroundView property based on if there is any data in the CollectionView or not. I have navigation which will change the data, and reloads the collection view (calling [self.collectionView reloadData]). For some reason I am getting very strange results. Firstly, sometimes when I set the property it appears on top of the collectionView cells and obscured them. Secondly when I try to change the property it does not change on screen. This is driving me nuts ! It seemed such a simple thing to implement!

So in Code. InviewDidLoad for the UICollectionViewController

- (void)viewDidLoad {
[self loadSections];
[self setupBackgroundView;
}

The Load sections method just loads the data I am using for the collection view, which then also calls a method to set the background view which decides what view to add based on if there is any data as below:

- (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;
}
}

Now when the view first loads, if there is no data and so no cells to display the background Image comes up correctly. I then change data and I now have some cells to show, the setupBackgroundImage is called and I can verify that the backgroundImage Property is set to nil (I have even breakpointed here and checked the value and it is nil). BUT the background image is still visible.

Additionally if I change the nil to another image this new image is never shown.

And even more strange. If I have some cells displayed and set a background image then this image is displayed neatly behind the cells. If I then reloadData with a new data set, then image is displayed in front of the cells, obscuring them. I have no idea how this happens as then background view should be behind all the others.

Does anyone know why this is happening. Is it getting cached anywhere? or am I just doing something silly ? I am at a total loss here - have spent more time on this than writing the custom layout that it uses!

like image 709
SimonB Avatar asked May 17 '13 08:05

SimonB


1 Answers

Try this

self.collectionView.backgroundView =[[UIView alloc]initWithFrame:self.collectionView.bounds]; 
UIImageView *imgVW=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"TakePhoto"]];
[self.collectionView.backgroundView addSubView:imgVW];
like image 179
Lithu T.V Avatar answered Nov 15 '22 05:11

Lithu T.V