How to add a Container View programmatically

A storyboard “container view” is just a standard UIView object. There is no special “container view” type. In fact, if you look at the view hierarchy, you can see that the “container view” is a standard UIView: To achieve this programmatically, you employ “view controller containment”: Instantiate the child view controller by calling instantiateViewController(withIdentifier:) on … Read more

add UIImage in CALayer

This is a general answer for the sake of future viewers. It is based on the question title rather than the details of the original question. How to add a UIImage to a CALayer You can add an image to a view’s layer simply by using its contents property: myView.layer.contents = UIImage(named: “star”)?.cgImage Note that … Read more

Apple Interface Builder: adding subview to UIImageView

You cannot add a subview to UIImageView in interface builder for reasons only known to Apple! You are right in saying that you can addSubview programmatically, but then, the overhead of setting autoresizing masks and placements of subviews should all be handled in code, which is cumbersome. So there is an easy workaround. Instead of … Read more

How to remove all subviews?

Edit: With thanks to cocoafan: This situation is muddled up by the fact that NSView and UIView handle things differently. For NSView (desktop Mac development only), you can simply use the following: [someNSView setSubviews:[NSArray array]]; For UIView (iOS development only), you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the … Read more

How can I loop through all subviews of a UIView, and their subviews and their subviews

Use recursion: // UIView+HierarchyLogging.h @interface UIView (ViewHierarchyLogging) – (void)logViewHierarchy; @end // UIView+HierarchyLogging.m @implementation UIView (ViewHierarchyLogging) – (void)logViewHierarchy { NSLog(@”%@”, self); for (UIView *subview in self.subviews) { [subview logViewHierarchy]; } } @end // In your implementation [myView logViewHierarchy];