iosswiftuivisualeffectviewuiblureffectuivibrancyeffect

UIBlurEffect and UIVibrancyEffect image doesn't show on a view controller's view


I came across an example on a book for learning iOS 13 programming. I put the program snippet in a view controller's view, but the image, a label with vibrancy effect on a blurred background, doesn't show on the controller's view.

The expected image is as follows:

enter image description here

The code for the program is as follows:

import UIKit
import CoreImage.CIFilterBuiltins

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        drawBlurAndVibrancyImage()

    }

    func drawBlurAndVibrancyImage () {
        let blurEffect = UIBlurEffect(style: .systemThinMaterial)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(blurView)
        let vibEffect = UIVibrancyEffect(blurEffect: blurEffect, style: .label)
        let vibView = UIVisualEffectView(effect: vibEffect)
        let lab = UILabel()
        lab.text = "Hello, world!"
        lab.sizeToFit()
        vibView.bounds = lab.bounds
        vibView.center = self.view.bounds.center
        vibView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
        blurView.contentView.addSubview(vibView)
        vibView.contentView.addSubview(lab)
    }
}

Thank you very much!


Solution

  • You are not providing any value to blurView's frame initially.

    let blurView = UIVisualEffectView(effect: blurEffect)
    blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.view.addSubview(blurView)
    

    You can add blurView.frame = self.view.bounds and you will start seeing the label and visual effect views.