简体   繁体   中英

Blur effect not appearing in UITableViewCell

I'm trying to add a blur effect to my view. I created the blur effect like so

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)


    return blurEffectView
    }()

Then I add it to the subview like so, and set up the constraints with it as well

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        let view = tableViewCell

        addSubview(view)
        view.addSubview(blurLabel)

 blurLabel.leftAnchor.constraint(equalTo: self.leftAnchor,constant:0).isActive = true
        //blurLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 178).isActive = true
        blurLabel.widthAnchor.constraint(equalToConstant: 375).isActive = true
        blurLabel.heightAnchor.constraint(equalToConstant: 180).isActive = true

But when I run the application it doesn't appear at all

Edit: As suggested by @HAS & @Fogmeister, you can also use translatesAutoResizingMaskIntoConstraints = false as it is better solution to use Auto Layout without specifying explicit frames.

You will have to assign frame to UIVisualEffectView like this:

 let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = CGRect(x: 0, y: 0, width: 60, height: 40) //give desirable frame
    return blurEffectView
 }()

If you would like, instead of giving explicit frames you can also provide your blurView's to any of your view or, subviews.

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)    
    blurEffectView.frame = myMainview.bounds //Blur effect's frame
    return blurEffectView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    // Use it somewhere using
    self.view.insertSubview(blurEffectView, belowSubview: myAnotherView)
    // You may also use any of the subviews too, instead of the self.view
    /// self.myView.insertSubview(blurEffectView, belowSubview: myAnotherView)
}

To fix this you just have to stop it automatically creating constraints. Like this...

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    // this line will stop constraints being added for a zero frame
    blurEffectView.translatesAutoResizingMaskIntoConstraints = false
    return blurEffectView
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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