gpt4 book ai didi

swift - UIView alpha 在第一次调用更改它后不会更新。 ( swift 4.2)

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:23 25 4
gpt4 key购买 nike

我有一个 UIView,我想在用户打开滑出菜单时将 alpha 从 0 更改为 0.5。当用户点击变暗区域时,alpha 应该返回到 0。目前,当点击菜单按钮时,alpha 变为 0.5,为 View 添加暗淡效果。但是,断点和打印语句显示,当点击 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")
})
}

最佳答案

showMenu 中创建的dimView 与第一行中创建的dimView 不同。您正在 showMenu 中创建一个全新的 dimView

解决此问题的一种方法是不在 showMenu 中创建新的 dimView,而是使用在外部声明的那个:

@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() })
}

关于swift - UIView alpha 在第一次调用更改它后不会更新。 ( swift 4.2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53825923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com