tags:

views:

28

answers:

1

Hi guyss, i have a view that addes a subview programmtically

    SelectionScreenTable *aSelectionScreenTableViewController = [[SelectionScreenTable alloc] initWithNibName:@"SelectionScreenTable" bundle:[NSBundle mainBundle]];

aSelectionScreenTableViewController.view.bounds = CGRectMake(0,0,955,520);
aSelectionScreenTableViewController.view.center = CGPointMake(528, 379);

[self.view addSubview:aSelectionScreenTableViewController.view];

Now i wish to remove it on clicked on a button and add it again so i did it wrote another 1 like this

SelectionScreenTable *viewController =[[SelectionScreenTable alloc]initWithNibName:@"SelectionScreenTable" bundle:nil];
viewController.view.bounds = CGRectMake(0,0,955,520);
viewController.view.center = CGPointMake(528, 379);

UIView *CV = [UIView alloc];
CV = [[self.view subviews]objectAtIndex:3]; 
[CV removeFromSuperview];
[CV release];

[self.view addSubview:viewController.view];

it Works but one thing i noticed was when it was removed and added on again. the

[self.view subviews]objectAtIndex:3 seems to change indexes? Because i can only click a certain number of times before the app crashes.

If so, should i do a increment where a variable + 1 everytime the button is clicked and use objectAtIndex:variable?

+2  A: 

Using the indexes seems like it'll be fragile in the long run, so is probably best avoided.

One approach would be to retain the pointer to the view in a member variable so you don't need to use objectAtIndex.

Another approach would be to do:

[CV setTag:5];

and instead of objectAtIndex, use:

[self.view withWithTag:5];

('5' is an arbitary choice - it should be a unique number within your program! It would be best to use a #define or enum to store the value - eg. #define MY_VIEW_TAG 5 and setTag:MY_VIEW_TAG etc)

JosephH
great! one question, how do i remove a tagged view from the current view? since i cant use [CV removeFromSuperView]
Kenneth
I think you can use [CV removeFromSuperView] still? Otherwise, [[self.view viewWithTag:5] removeFromSuperView] should do it
JosephH
cool. great. it worked.! thanks dude
Kenneth