Search This Blog

Sunday, October 22, 2017

How to remove all subviews of a view in Swift?

Following task - remove all subViews of current view. Let's see how we can implement this.

For example we create UIView and add UILabel to it.
var containerView = UIView()
containerView.addSubview(UILabel(frame: CGRect.zero))

1. Simple For Loop
for subView in containerView.subviews {
    subView.removeFromSuperview()
}

2. ForEach Loop
containerView.subviews.forEach {
    $0.removeFromSuperview()
}

3. Using Map Function
containerView.subviews.map { $0.removeFromSuperview() }

4. Making Extension

If we want to make removing enable for all views in project then let's create Extension.
extension UIView {   
    func removeAllSubView() {
        self.subviews.forEach { $0.removeFromSuperview() }
    }
}

containerView.removeAllSubView()

5. Going Universal with Generics

We can go further and make our Extension universal with Generics. Now You can specify which type of subViews You want to remove.
extension UIView {
    
    func removeAllSubViewOfType<T: UIView>(type: T.Type) {
        self.subviews.forEach {
            if ($0 is T) {
                $0.removeFromSuperview()
            }
        }
    }
}

containerView.removeAllSubViewOfType(type: UILabel.self)

6. The Same but Using Filter and Map Functions

The same as above. But here we use chain of High-order functions.
extension UIView {
    
    func removeAllSubViewOfTypeUsingHOF<T: UIView>(type: T.Type) {
        self.subviews.filter({ $0 is T }).map({ $0.removeFromSuperview() })
    }
}

containerView.removeAllSubViewOfTypeUsingHOF(type: UILabel.self)

7 comments:

  1. Really nice article. its really helpful me. Very interesting and good post thanks for sharing such a good blog.
    -Web Development Services

    ReplyDelete
  2. After a long time i found a unique and on purpose information about Custom Designed Websites. Can't wait to have more from you.

    ReplyDelete
  3. This article impresses me with its well-researched material and good writing. I couldn't put this book down since I was so engrossed in it. Your work and skill have impressed me. Thank you a lot. It can be beneficial to those who want to learn more about Best Custom Websites

    ReplyDelete
  4. Thank you very much for drawing my notice to this. Your blog is jam-packed with useful facts. Until I read that, I would have no idea. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Web Design USA

    ReplyDelete
  5. This is a great article! Thank you very much. I really need these suggestions. An in-depth explanation is of great benefit. Incredibly inspiring to see how you write. Custom Website

    ReplyDelete
  6. Great share!One of the best blogs I have Ever Seen. Keep going!
    iOS App Testing Services

    ReplyDelete
  7. Amazing write-up! The blog was very informative. Keep it up!
    Custom Website/a>

    ReplyDelete