简体   繁体   中英

UIImageView, constraints and a blur programmatically

I want to create a UIImageView with a blur and constraints. But the blur doesn't want to work with constraints.

My code:

    var notifBackground: UIImageView!
    notifBackground = UIImageView()
    notifBackground.backgroundColor = UIColor.clear
    view.addSubview(notifBackground)

    notifBackground.translatesAutoresizingMaskIntoConstraints = false
    notifBackground.widthAnchor.constraint(equalToConstant: 200).isActive = true
    notifBackground.heightAnchor.constraint(equalToConstant: 200).isActive = true
    notifBackground.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    notifBackground.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.regular))
    blur.frame = notifBackground.bounds
    view.addSubview(blur)

At the time you're setting the bounds of the blur to the same bounds of the imageview, the layout constraints has not been processed yet. What you have to do is to set similar constraints to the blur as well. By doing this, the blur will have similar bounds and appear on top of the imageview.

BLUR EFFECT

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

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