A. Sola
A. Sola

Reputation: 117

Remove blur effect in tableview cell in Swift

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?

Upvotes: 0

Views: 1413

Answers (2)

jDutton
jDutton

Reputation: 941

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

Upvotes: 0

Dave Batton
Dave Batton

Reputation: 8845

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.

Upvotes: 3

Related Questions