从ViewDidLoad调用后,子视图不会删除

时间:2019-08-22 20:39:16

标签: swift subview

我添加了一个UIBlurEffect,该函数具有在从服务器加载数据之前加载它的功能。我添加了一个boolean参数来激活或停用它。

func addingEffectLayerWithSpinner(active: Bool){
    let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    if active {
        view.addSubview(blurEffectView)
    } else {
        //This one is not working
        blurEffectView.removeFromSuperview()
    }
}

然后在viewDidLoad中,我将false传递给那个函数以删除UIBlueEffect视图,但是它不起作用,能帮我解决问题吗?

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    addingEffectLayerWithSpinner(active: true)

    profile.showingProfile { result in
        switch result {
        case .success(_):
            // Sucesss response from server
            DispatchQueue.main.async {
                self.nameLabel?.text = nameOfUser!
                self.avatar?.downloaded(from: avatarUrl!)

                //This one is not working
                self.addingEffectLayerWithSpinner(active: false)
            }
            // failed response from server
        case .failure(let error):
            print(error)
        }

    }
}

1 个答案:

答案 0 :(得分:0)

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)

问题在这里。每次调用上面的blurEffectView时,都会准备一个新的UIVisualEffectView,它与现在呈现的内容有所不同。

blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
if active {
    view.addSubview(blurEffectView)
} else {
    //This one is not working
    blurEffectView.removeFromSuperview()
}

因此,您可以考虑将blurEffectView保存为属性,然后调用以将其删除。

var  blurEffectView :  UIVisualEffectView!

func addingEffectLayerWithSpinner(active: Bool){

//introduce a false condition early: 
if !active {  blurEffectView.removeFromSuperview()
 return
} 

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)

blurEffectView = UIVisualEffectView(effect: blurEffect)
//remove `let` here
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    view.addSubview(blurEffectView)

}