Search code examples
iosiphoneswiftcgrectswift4

delete subview that use with imageView


I have a map picture in my ImageView and I want a red dot for user current location so I use this 3 lines of code for creating red dot above my ImageView

let overlay: UIView = UIView(frame: CGRect(x: xcorIn * 0.822, y:  ycorIn * 1.03, width: 5, height: 5))

overlay.backgroundColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1)

imageView.addSubview(overlay)

all I want is after of 2 seconds of red dot appear it must disappear

so I try this

 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
            self.imageView.delete(overlay)

})

delay function seem work but

self.imageView.delete(overlay)

return me this error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView delete:]: unrecognized selector sent to instance 0x7f8bef712df0'


Solution

  • You need to remove overlay from the superView. You could either do this:

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
        overlay.removeFromSuperview()
    })
    

    Or if you don´t have overlay globally, you could do this. Add a tag to your overlay and then do this:

    let overlay: UIView = UIView(frame: CGRect(x: 100, y:  100, width: 5, height: 5))
    overlay.tag = 0
    overlay.backgroundColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1)
    imageView.addSubview(overlay)
    
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
        for subView in self.imageView.subviews {
            if subView.tag == 0 {
                subView.removeFromSuperview()
            }
        }
    })