xcode Removing Some Subviews from view

北城以北 提交于 2019-11-30 07:04:34

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];
    }
}

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

self.view.subviews.filter({$0.tag == 7}).forEach({$0.removeFromSuperview()})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!