Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

naphatkrit

macrumors member
Original poster
Jul 18, 2011
38
0
Hi,

I want to use a single instance of a subclass of UIView (so that it doesn't have to be redrawn) as the background of the cells of my UICollectionView. The way I have set it up is, in the UICollectionView, declare a variable (nonatomic, strong) of the class for my background view. In viewDidLoad, I initialize the view with the frame (0, 0, width, height). In my subclass of UICollectionViewCell, I have a variable declared for the background (nonatomic, weak). Then back in my CollectionView, in the cellForIndexPath method, I assign the initialized background view to the cell's background view and call "setNeedsDisplay" to force a redraw. This works, but only for the first cell, not any other. Is my approach correct?
 

Duncan C

macrumors 6502a
Jan 21, 2008
853
0
Northern Virginia
Hi,

I want to use a single instance of a subclass of UIView (so that it doesn't have to be redrawn) as the background of the cells of my UICollectionView. The way I have set it up is, in the UICollectionView, declare a variable (nonatomic, strong) of the class for my background view. In viewDidLoad, I initialize the view with the frame (0, 0, width, height). In my subclass of UICollectionViewCell, I have a variable declared for the background (nonatomic, weak). Then back in my CollectionView, in the cellForIndexPath method, I assign the initialized background view to the cell's background view and call "setNeedsDisplay" to force a redraw. This works, but only for the first cell, not any other. Is my approach correct?

No, that approach is not correct. A view can only have a single superview. Adding your view instance to a second cell will remove it from the previous view.

You're going to have to create multiple instances of your view.

Alternately, you could capture a snapshot of your view to a UIImage, and install that image as the contents of multiple image views. UIImage objects CAN belong to more than one view at a time.
 

naphatkrit

macrumors member
Original poster
Jul 18, 2011
38
0
Alternately, you could capture a snapshot of your view to a UIImage, and install that image as the contents of multiple image views. UIImage objects CAN belong to more than one view at a time.

Which would you recommend, performance-wise?
 

Duncan C

macrumors 6502a
Jan 21, 2008
853
0
Northern Virginia
Which would you recommend, performance-wise?

It doesn't make much difference. Views cache their contents by default, and only get redrawn if something changes. Don't call setNeedsDisplay on the view unless something changed where the view needs to be redrawn but the system doesn't do it automatically.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.