将UIVisualEffectView明显添加到UICollectionViewCell

时间:2018-08-29 08:33:19

标签: ios uicollectionview uivisualeffectview

我的UICollectionView的单元格很多。细胞上有需要模糊的图像。这就是为什么我要向UIVisualEffectView添加具有模糊效果的image views。单元格就像页面-每个单元格占据整个屏幕。

问题出在第二个单元格上。当它出现时,模糊的视图被明显地添加并且很丑陋。当其余的单元格在屏幕上可见并且可以时,它们的视图已经模糊。这是我用来添加blur view的代码:

class ImageCell: UICollectionViewCell {

    @IBOutlet weak var mainImageView: UIImageView!
    @IBOutlet weak var backgroundImageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        let regularBlur = UIBlurEffect(style: .regular)
        let blurView = UIVisualEffectView(effect: regularBlur)
        blurView.frame = backgroundImageView.bounds
        blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        backgroundImageView.addSubview(blurView)

    }
}

2 个答案:

答案 0 :(得分:1)

修改代码:

class ImageCell: UICollectionViewCell {

    @IBOutlet weak var mainImageView: UIImageView!
    @IBOutlet weak var backgroundImageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        backgroundImageView.isHidden = true
        let regularBlur = UIBlurEffect(style: .regular)
        let blurView = UIVisualEffectView(effect: regularBlur)
        blurView.frame = backgroundImageView.bounds
        blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        backgroundImageView.addSubview(blurView)
        backgroundImageView.isHidden = false
    }
}

答案 1 :(得分:0)

您可以这样编码:

class ImageCell: UICollectionViewCell {

@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var backgroundImageView: UIImageView!

let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .regular))


override func awakeFromNib() {
    super.awakeFromNib()

    blurView.frame = backgroundImageView.bounds
    blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    backgroundImageView.addSubview(blurView)
}

override func prepareForReuse() {
        blurView.isHidden = true
    }
}