iOS UIView Programmatically manage UIView insertion and deletion into and from another UIView

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Suppose you have a parentView into which you want to insert a new subView programmatically (eg. when you want to insert an UIImageView into a UIViewController's view), than you can do it as below.

Objective-C

[parentView addSubview:subView];

Swift

parentView.addSubview(subView)

You can also add the subView below another subView2, which is already a sub view of parentView using the following code:

Objective-C

[parentView insertSubview:subView belowSubview:subView2];

Swift

parentView.insertSubview(subView, belowSubview: subView2)

If you want to insert it above subView2 you can do it this way:

Objective-C

[parentView insertSubview:subView aboveSubview:subView2];

Swift

parentView.insertSubview(subView, aboveSubview: subView2)

If somewhere in your code you need to bring a certain subView to front, so above all the others parentView's subviews, you can do it like this:

Objective-C

[parentView bringSubviewToFront:subView];

Swift

parentView.bringSubviewToFront(subView)

Finally, if you want to remove subView from parentView, you can do as below:

Objective-C

[subView removeFromSuperview];

Swift

subView.removeFromSuperview()


Got any iOS Question?