xcode addSubView 的正确使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7141551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:46:33  来源:igfitidea点击:

correct use of addSubView?

iphonexcodeaddsubview

提问by Kyle Parisi

I currently don't have any problems using:

我目前在使用时没有任何问题:

-(IBAction)products:(id)sender {
    products = [[Products alloc] initWithNibName:@"Products" bundle:nil];
    [self.view addSubview:products.view];
}

I tied this action to buttons to change my views. I'm sure this isn't correct though because the views are being stacked right? Will my application crash because of this? Know of any good sample code to switch views via IBAction?

我将此操作绑定到按钮以更改我的视图。我确定这不正确,因为视图正在堆叠对吗?我的应用程序会因此而崩溃吗?知道通过 IBAction 切换视图的任何好的示例代码吗?

回答by Akshay

If you are adding subviews that will cover the entire superview, you may consider removing an existing subview before adding a new one. You can do this by tagging views & then removing them.

如果您要添加覆盖整个超视图的子视图,您可以考虑在添加新子视图之前删除现有子视图。您可以通过标记视图然后删除它们来做到这一点。

While adding a view, assign it a tag-

添加视图时,为其分配一个标签-

products.view.tag = 1; //any number you want
[self.view addSubview:products.view];

To remove the older view, fetch it & remove it-

要删除旧视图,请获取并删除它-

UIView* subview = [self.view viewWithTag:1]; //Use the same number
[subview removeFromSuperview];
//now add a new view

HTH,

哈,

Akshay

阿克谢

回答by P.J

Adding multiple views make your application slow but it will not crash..

添加多个视图会使您的应用程序变慢,但不会崩溃。

You can remove all views from superview which will solve all your issues

您可以从超级视图中删除所有视图,这将解决您的所有问题

Hope it works..

希望它有效..