Joey
Joey

Reputation: 621

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'

Upvotes: 0

Views: 839

Answers (3)

casillas
casillas

Reputation: 16793

You are getting that error because there is no delete method in the imageView, but there is a method called removeFromSuperview.

You are going to remove the overlay from the SuperView

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

Or:

self.overlay.hidden = true

Or try the following if your reference to it was a strong reference, make sure to nil that strong reference:

overlay= nil 

Or animate without using dispatchQueue:

UIView.animate(withDuration: 0.5, delay: 0.3, options: [.repeat, .curveEaseOut, .autoreverse], animations: {
    self.overlay.alpha = 0
}, completion: nil)

Upvotes: 1

Bharath
Bharath

Reputation: 2114

You can remove the dot by using its reference and "removeFromSuperview()" method

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)

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

Upvotes: 1

Rashwan L
Rashwan L

Reputation: 38833

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

Upvotes: 1

Related Questions