我有一个UIView,当用户打开滑出菜单时,我想在其中将alpha值从0更改为0.5。当用户点击变暗的区域时,alpha值应回到0。当前,当轻按菜单按钮时,alpha值将变为0.5,从而为视图添加了暗淡效果。但是,一个断点和打印语句显示,当点击UIView时,将alpha更改回0的行将运行,但是UI仍显示0.5 alpha。我看过的所有地方的代码都完全相同,所以我不确定自己在做什么错。
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")
})
}
答案 0 :(得分:2)
在dimView
中创建的showMenu
与第一行中创建的dimView
不同。您正在dimView
中创建一个全新的showMenu
。
解决此问题的一种方法是不在dimView
中创建新的showMenu
,而改用在外部声明的变量:
@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() })
}