Supratik Majumdar Supratik Majumdar - 1 month ago 22
iOS Question

Remove View from SuperView with delay: Swift 3

I am trying to remove a view form the superView with a delay. I have the objective-c code for the same but an not able to implement it in Swift.

Code Snippet:

[self performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:6.5];

Answer

You can dispatch a closure to run after some delay and remove self from superview in the callback:

DispatchQueue.main.asyncAfter(deadline: .now() + 6.5) {
    self.removeFromSuperview()
}

If you really want to use performSelector approach, here it is:

self.perform(#selector(self.removeFromSuperview), with: nil, afterDelay: 6.5)