viewWithTag and addSubview

旧巷老猫 提交于 2019-12-23 16:47:18

问题


I am trying to reuse the label by making a call to viewWithTag when I press the UIButton. The code looks ok when it is executed the first time, but is it leaking on executing it multiple times due to line 7? Also is it just better to remove the label from the superview, alloc and addSubview instead of using viewWithTag?

1. UILabel *label = (UILabel *)[self.view viewWithTag:100];
2. if(label == nil) {
3.   label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease];
4.   label.tag = 100;
5. }
6. 
7. [self.view addSubview:label];

回答1:


Move the code [self.view addSubview:label]; inside your if block. When your if condition is false, that means the label is already part of of your viewcontroller's view hierarchy, so if you add it again like in your original code it will be double retained.

UILabel *label = (UILabel *)[self.view viewWithTag:100];
if (!label) {
    label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease];
    label.tag = 100;
    [self.view addSubview:label];
}



回答2:


If you are using a .xib or storyboard just link it with an IBOutlet.

If you'r using code only, try to save it as a private variable.



来源:https://stackoverflow.com/questions/9691865/viewwithtag-and-addsubview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!