John Nolan
John Nolan

Reputation: 65

UIView alpha does not update after first call to change it. (Swift 4.2)

I have a UIView on which I want to change the alpha from 0 to 0.5 when the user opens a slide out menu. When the user taps the darkened area the alpha should go back to 0. Currently, when the menu button is tapped the alpha changes to 0.5 adding a dimming effect to the view. However, a breakpoint and print statement show that when tapping the UIView the line to change the alpha back to 0 runs, but the UI still shows a 0.5 alpha. Everywhere I have looked the code is exactly the same, so I am unsure what I am doing wrong.

let dimView = UIView()
func setupMenuButton() {
    let menuButton = UIBarButtonItem(title: "Menu", style: .plain, target: self, action: #selector(showMenu))
    navigationItem.rightBarButtonItem = menuButton
}

@objc func showMenu() {
    //TODO: present menu and dim background
    if let window = UIApplication.shared.keyWindow {
        let dimView = UIView()
        dimView.backgroundColor = UIColor.black
        dimView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissDimView)))
        window.addSubview(dimView)
        dimView.frame = window.frame
        dimView.alpha = 0
        UIView.animate(withDuration: 0.5, animations: {
            dimView.alpha = 0.5
        })
    }
}

@objc func dismissDimView() {
    UIView.animate(withDuration: 0.5, animations: {
        self.dimView.alpha = 0
        print("dim view is not transparent")
    })
}

Upvotes: 2

Views: 530

Answers (1)

Sweeper
Sweeper

Reputation: 271775

The dimView created in showMenu is not the same dimView created in the first line. You are creating a brand new dimView in showMenu.

One way to fix this is to not create a new dimView in showMenu, and use the one declared outside instead:

@objc func showMenu() {
    //TODO: present menu and dim background
    if let window = UIApplication.shared.keyWindow {
        // notice I deleted a line here
        dimView.backgroundColor = UIColor.black
        dimView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissDimView)))
        window.addSubview(dimView)
        dimView.frame = window.frame
        dimView.alpha = 0
        UIView.animate(withDuration: 0.5, animations: {
            dimView.alpha = 0.5
        })
    }
}

@objc func dismissDimView() {
    UIView.animate(withDuration: 0.5, animations: {
        self.dimView.alpha = 0
        // here I remove the dimView from the window so that it can be added back in the next time showMenu is called
    }, completion: { [weak self] _ in self?.dimView.removeFromSuperView() })
}

Upvotes: 2

Related Questions