A single instance of a UIView subclass across the cells of UICollectionView

Discussion in 'iPhone/iPad Programming' started by naphatkrit, Feb 1, 2013.

  1. macrumors member

    Joined:
    Jul 18, 2011
    #1
    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?
     
  2. macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #2
    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.
     
  3. thread starter macrumors member

    Joined:
    Jul 18, 2011
    #3
    Which would you recommend, performance-wise?
     
  4. macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #4
    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.
     

Share This Page