Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redraw non-visible UICollectionViewCell's after rotation ready for when reuse occurs?

How to redraw non-visible UICollectionViewCell's ready for when reuse occurs???

One approach I thought of was per the code in the Layout Cell prepareForReuse function, however whilst it works it non-optimal as it causes more re-drawing then required.

Background: Need to trigger drawRect for cells after an orientation change that are not current visible, but pop up to be used and haven't been redraw, so so far I can only see that prepareForReuse would be appropriate. Issue is I'm re-drawing all "reuse" cells, whereas I really only want to redraw those that initially pop up that were created during the previous orientation position of the device.

ADDITIONAL INFO: So currently I'm doing this:

In ViewController:

override func viewWillLayoutSubviews() {
    // Clear cached layout attributes (to ensure new positions are calculated)
    (self.cal.collectionViewLayout as! GCCalendarLayout).resetCache()
    self.cal.collectionViewLayout.invalidateLayout()

    // Trigger cells to redraw themselves (to get new widths etc)
    for cell in self.cal?.visibleCells() as! [GCCalendarCell] {
        cell.setNeedsDisplay()
    }

    // Not sure how to "setNeedsDisplay" on non visible cells here?
}

In Layout Cell class:

override func prepareForReuse() {
    super.prepareForReuse()
    // Ensure "drawRect" is called (only way I could see to handle change in orientation
    self.setNeedsDisplay() 
    // ISSUE: It does this also for subsequent "prepareForReuse" after all
    // non-visible cells have been re-used and re-drawn, so really
    // not optimal
}

Example of what happens without the code in prepareForReuse above. Snapshot taken after an orientation change, and just after scrolling up a little bit:

enter image description here

like image 934
Greg Avatar asked Oct 21 '15 12:10

Greg


1 Answers

I think I have it now here:

import UIKit

@IBDesignable class GCCalendarCell: UICollectionViewCell {
    var prevBounds : CGRect?

    override func layoutSubviews() {
        if let prevBounds = prevBounds {
            if !( (prevBounds.width == bounds.width) && (prevBounds.height == bounds.height) ) {
                self.setNeedsDisplay()
            }
        }
    }

    override func drawRect(rect: CGRect) {
        // Do Stuff
        self.prevBounds = self.bounds
    }

}

Noted this check didn't work in "prepareForReuse" as at this time the cell had not had the rotation applied. Seems to work in "layoutSubviews" however.

like image 128
Greg Avatar answered Nov 08 '22 09:11

Greg