I am using this code to create and delete a view. All conditions are completed, but the view is not deleted. How to fix it?
@objc func action(sender: UIButton) {
let a = UIView()
a.backgroundColor = .green
if settingsButtonState == true {
settingsButtonState = false
a.removeFromSuperview()
print("delete") // this condition is completing but not remove view
} else {
settingsButtonState = true
view.frame = UIScreen.main.bounds
view.addSubview(a)
print("add")
}
}
You are creating a new UIView
every time action
is called, so when the settingsButtonState
is true
, a
has no super view to be removed from. You need to store a reference to a
and then remove that from the superview.
// Store the view as a property
private let a: UIView?
@objc func action(sender: UIButton) {
if a == nil {
a = UIView()
}
a.backgroundColor = .green
if settingsButtonState == true {
settingsButtonState = false
a.removeFromSuperview()
} else {
settingsButtonState = true
view.frame = UIScreen.main.bounds
view.addSubview(a)
}
}