Tag Archives: UIView

iPhone – Add and Remove Subviews

The layout of an UIView in iPhone Application can be created and modified either by the Interface Builder or by code. If you make it by Interface Builder, you have to wire the items u created to File Owner.

On the other hand, u can make an Item on the UIView by code. The following example will created a “Hello World” UILabel at coordinate (10, 15) with size equals to 40 x 20;

// Create the UILabel instance
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 40, 20)];
// Set the tag of aLabel
aLabel.tag = 1;
// Set the text
aLabel.text = @"Hello World";
// Add the UILabel view to UIView associated with the controller
[self.view addSubview:aLabel];
// Release the memory
[aLabel release];


You can add different items such as UIImageView, UITextField etc. Please note that the view tag is the only field to distinguish different subviews.

To remove all the subviews except the one with tag equals to 1, you can use

for (UIView *subview in [self.view subviews]) {
	// Only remove the subviews with tag not equal to 1
	if (subview.tag != 1) {
		[subview removeFromSuperview];


Done =)

Update @ 2011-06-18: Added the “Release the memory” code. Thanks Luke. =)