So I am trying to blur the background view of the UICollectionView cell. This is what I am trying to accomplish:
I tried using this extension:
extension UIView {
func applyBlurEffect(_ style: UIBlurEffect.Style = .dark) {
let blurEffect = UIBlurEffect(style: style)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(blurEffectView)
}
}
And use it like this:
cell.backgroundColor = .clear
cell.backgroundView?.applyBlurEffect()
But this is the result I get:
Also tried changing from dark to light, but no changes.. What am I doing wrong here?
EDIT: Added UICollectionViewCell class:
import UIKit
class MenuCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var categoryEmoji: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var lineView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
contentView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(blurEffectView)
blurEffectView.layer.cornerRadius = 20
blurEffectView.clipsToBounds = true
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
// constrain blur view to all 4 sides of contentView
blurEffectView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
blurEffectView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
blurEffectView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
blurEffectView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
])
}
}
And this is the result I have now. The label's are also blurred now.:



Don't try to modify the cell's background view. Much easier to add a
UIVisualEffectViewto the cell.Here's a very simple example. I created a background image similar to what you have in your post, and I used
UIBlurEffect(style: .light)since the dark background doesn't really show the effect much:BlurCell class
Simple example controller class
Result: