开发者

iPhone - removing subview and adding it again, [self.views subviews] objectAtIndex changes?

开发者 https://www.devze.com 2023-01-07 01:37 出处:网络
i have a view that addes a subview programmtically SelectionScreenTable *aSelectionScreenTableViewController = [[SelectionScreenTable alloc] initWithNibName:@\"SelectionScreenTable\" bundle:[NSBundle

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);
aSelectionScreenTabl开发者_C百科eViewController.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?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消