简体   繁体   English

在Swift中删除表格视图单元中的模糊效果

[英]Remove blur effect in tableview cell in Swift

I make this in my IF clausure, in the cellForRowAtIndexPath method: 我在IF声明中的cellForRowAtIndexPath方法中做到了这一点:

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. 在我的ELSE声明中,我想从cell.attachedImage中删除效果。

How can I do it? 我该怎么做?

cellForRowAtIndexPath should not be adding subviews to cells. cellForRowAtIndexPath不应将子视图添加到单元格。 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. 但是,这样做的逻辑应该在单元格子类中。

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: 最简单的方法是将其存储在自定义UITableViewCell实现中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM