xcode Removing Some Subviews from view

前端 未结 2 1967
广开言路
广开言路 2020-12-30 06:55

Greetings all,

I am a noob and I have been trying to work through this for a few days.

I am adding images to a view via UItouch. The view contains a backgro

相关标签:
2条回答
  • 2020-12-30 07:24

    What you need is a way of distinguishing the added UIImageView objects from the background UIImageView. There are two ways I can think of to do this.

    Approach 1: Assign added UIImageView objects a special tag value

    Each UIView object has a tag property which is simply an integer value that can be used to identify that view. You could set the tag value of each added view to 7 like this:

    myImage.tag = 7;
    

    Then, to remove the added views, you could step through all of the subviews and only remove the ones with a tag value of 7:

    for (UIView *subview in [self.view subviews]) {
        if (subview.tag == 7) {
            [subview removeFromSuperview];
        }
    }
    

    Approach 2: Remember the background view

    Another approach is to keep a reference to the background view so you can distinguish it from the added views. Make an IBOutlet for the background UIImageView and assign it the usual way in Interface Builder. Then, before removing a subview, just make sure it's not the background view.

    for (UIView *subview in [self.view subviews]) {
        if (subview != self.backgroundImageView) {
            [subview removeFromSuperview];
        }
    }
    
    0 讨论(0)
  • 2020-12-30 07:37

    A more swiftly code for approach #1 in only one functional line of code :

    self.view.subviews.filter({$0.tag == 7}).forEach({$0.removeFromSuperview()})
    
    0 讨论(0)
提交回复
热议问题