Mostafa Mohamed Raafat Mostafa Mohamed Raafat - 1 year ago 64
iOS Question

removeFromSuperview() view Not removed from first time

Ok I have this case where I insert 5 Views programmatically using this method:

let starView = UIImageView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.width))

// Set Image & Alpha
starView.image = #imageLiteral(resourceName: "star")
starView.alpha = 1
starView.tag = starIndex

// Add to Super View

Please note that starIndex for the 5 views are 1,2,3,4,5 consequently

It's Straightforward.

After a while when an event happens, I use another method to remove these views using this method:

func removeOldStars() {
for index in 1...5 {
if let foundView = view.viewWithTag(index) {

What happens here as a result is that the last element only "number 5" is removed. I have tried several trial and error and found this weird behavior. When I remove the view twice using the tag number it works. So for example, if I want to remove view with tag number 3 if I write


It works!!! if just one time it doesn't do anything. I thought maybe the view is added twice and so it need to be removed twice to notice it, but i Debugged it and no the view is added single time.

I removed the view in the main thread to be sure that its not threading issue not no its not the problem.

I would appreciate your help because this is so weird i really need to understand whats happening here.

Answer Source

Tags, in general, are a brittle way to reference views. As @Paulw11 mentioned, this is very likely an issue with other subviews having identical tag values. In this case, I would hold on to instances of the UIImageViews, and then in the removeOldStars method, iterate through and call removeFromSuperview on the instance directly.

//instantiate empty array of UIImageView
var starViews = [UIImageView]()

//assuming your add method name..
func addStar() {

  //your code above up to...


func removeOldStars() {  
    for view in starViews {
        //maybe explicitly de allocate the view depending