Joe Huang Joe Huang - 7 months ago 142
Swift Question

How to add blur effect on status bar in iOS 11 correctly without warnings?

I used to add blur effect on status bar with following code:

// Add blur effect on status bar
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.translatesAutoresizingMaskIntoConstraints = false
blurEffectView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
blurEffectView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
blurEffectView.topAnchor.constraint(equalTo: self.topLayoutGuide.topAnchor).isActive = true
blurEffectView.bottomAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true

It works since Xcode 6 or 7, even for Xcode 9. However, the last two lines start to give warning since Xcode 9:

'topLayoutGuide' was deprecated in iOS 11.0: Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor

By following the warning, if I change
to the suggested value, the result is not right (all screen is blank).

How to add blur effect on status bar in iOS 11 correctly without warnings?

Mia Mia
Answer Source

Since OP doesn't like using inset heights, just do this:

blurEffectView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
blurEffectView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
blurEffectView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
blurEffectView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download