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. =)

15 thoughts on “iPhone – Add and Remove Subviews”

  1. Hi,

    I am having trouble, I am trying to add subviews to a view, like a grid each grid is a UIVIew a sub view.

    My algorithm can only add 4, 5 or more grids won’t work.

    Maybe it is a app delegate issue, I don’t know what the bug is, but I hope I find out soon,

    Thanks

    Like

  2. i have 2 uiview in my xib file and
    i have create a button and the action of that button is wen it pressed it goes to the secont view i have done it using [self.view subviews:view1]; function
    but the problem cums wen wen i give the similar action to the button on the second uiview
    using the same function what shud i do….??

    Like

  3. hey cud u give me a link of a gud tutorial for x.code and ios development as i have just started it
    and i am not having much of an idea abt it…..!

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.