0

I make this in my IF clausure, in the cellForRowAtIndexPath method:

let blurEffect = UIBlurEffect(style: .Light)
        let visualEffect = UIVisualEffectView(effect: blurEffect)

        visualEffect.frame = cell.attachedImage.bounds

        cell.attachedImage.addSubview(visualEffect)

In my ELSE clausure I want to remove the effect from cell.attachedImage.

How can I do it?

A. Sola
  • 107
  • 1
  • 12

2 Answers2

3

cellForRowAtIndexPath should not be adding subviews to cells. It's problematic because cells get reused, and if you're not keeping references to what you've added, you'll end up adding views multiple times and that can cause scrolling speed problems, as well as other bugs.

The proper approach is to create a cell subclass that already has the views set up. Your subclass can contain properties that reference the views so you can change, hide, move, or remove them from their superview as needed. But the logic for this should be in the cell subclass.

Dave Batton
  • 8,795
  • 1
  • 46
  • 50
  • Good call. Emphasis on the "hide" part: cells get reused, so if one cell instance removes the blur view for one row, then that cell gets reused for a different row that wants the blur, you'll have to reconstruct the blur view. Hiding/showing a subview is much less expensive. – rickster Jan 15 '16 at 19:40
0

You just need to remove the visual effect view from it's superview. The trick is finding the right view to remove when the cell is recycled. The easiest way to do that would be to store it in a custom UITableViewCell implementation:

class CustomTableViewCell: UITableViewCell {
    var visualEffectView: UIView?
    var attachedImage: UIImageView!
    // other views, including outlets

    func setupIsBlurred(isBlurred: Bool) {
        if isBlurred {
            if self.visualEffectView == nil {
                let blurEffect = UIBlurEffect(style: .Light)
                let visualEffectView = UIVisualEffectView(effect: blurEffect)

                visualEffectView.frame = self.attachedImage.bounds

                self.attachedImage.addSubview(visualEffectView)

                self.visualEffectView = visualEffectView
            }
        } else {
            self.visualEffectView?.removeFromSuperview()
            self.visualEffectView = nil
        }
    }
}
jDutton
  • 941
  • 11
  • 13