Reputation: 5658
I have a problem where if I remove subview from super view and then when I push to another VC and come back all the removed subview reappear in the view I have tried everything and checked my code if viewDidApper too.
//HERE IS HOW I ADD VIEWS
func addusers() {
for user in 0...5 {
let radarButton = PRButton(frame: CGRect(x: 0, y: 0, width: itemSize.width, height: itemSize.height+14))
radarButton.profileButton?.setImage(UIImage(named: "dummy-avatar.png"), for: UIControlState())
radarButton.profileName.setTitle("test \(user)", for: .normal)
repeat {
let center = generateCenterPointInRadar()
radarButton.center = CGPoint(x: center.x, y: center.y)
} while (itemFrameIntersectsInOtherItem(radarButton.frame))
radarButton.profileButton?.addTarget(self, action: #selector(didTapUser), for: .touchUpInside)
radarButton.profileName?.addTarget(self, action: #selector(didTapUser), for: .touchUpInside)
self.addSubview(radarButton)
items.append(radarButton)
}
}
//HERE IS HOW I REMOVE VIEWS
func removeAllUsers() {
for view in self.subviews {
if view is PRButton {
view.removeFromSuperview()
}
}
items.removeAll()
}
//Remove from superview
override func removeFromSuperview() {
UIView.beginAnimations("", context: nil)
UIView.setAnimationDuration(1)
self.alpha = 0
UIView.setAnimationDidStop(Selector(("callSuperRemoveFromSuperview")))
UIView.commitAnimations()
}
fileprivate func callSuperRemoveFromSuperview() {
super.removeFromSuperview()
}
Thanks in advance
Upvotes: 1
Views: 193
Reputation: 71
I looked at the test project.
I think I found the problem, it was at the override func removeFromSuperview()
I comment out it and edit the removeAllUsers()
func removeAllUsers() {
for view in self.subviews {
if view is PRButton {
UIView.animate(withDuration: 1, animations: {
view.alpha = 0
}, completion: { (finished) in
view.removeFromSuperview()
})
}
}
items.removeAll()
}
Now I don't see any duplicate users while I'm back to the viewController
Upvotes: 2
Reputation: 77462
First thing to look at...
In PRButton
you override removeFromSuperview()
-- but your structure is incorrect and you never actually remove the view.
Replace it with this:
override func removeFromSuperview() {
UIView.animate(withDuration: 1.0, animations: ({
self.alpha = 0.0
}), completion: { _ in
self.callSuperRemoveFromSuperview()
})
}
You could also simply call super.removeFromSuperview()
instead of your additional self.callSuperRemoveFromSuperview()
function.
Get to know the Debug View Hierarchy
feature... you would have seen that immediately.
Upvotes: 1