[英]How to remove itself and superview from super superview?
I have a UIViewController
classes A
and B
. 我有一个UIViewController
类A
和B
A
loads B
using: [A.view addSubView B.view]
. A
使用以下方法加载B
: [A.view addSubView B.view]
。
B
has a navigation bar with a Back button. B
有一个带有“后退”按钮的导航栏。 I want to go back to A
when I click it, so in the selector I tried [self.view removeFromSuperview]
, but it only removed the navigation bar. 当我单击A
时,我想回到A
,因此在选择器中尝试了[self.view removeFromSuperview]
,但它仅删除了导航栏。 Then I tried [self.view.superview removeFromSuperview]
, it still just removed the navigation bar. 然后我尝试了[self.view.superview removeFromSuperview]
,它仍然只是删除了导航栏。 What should I do? 我该怎么办?
Also, another minor issue with the Back button: setting it's title. 另外,“后退”按钮的另一个小问题是:设置标题。 I tried these two ways, but it still displays "Back". 我尝试了这两种方法,但仍显示“返回”。
navItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Chapter" style:UIBarButtonItemStylePlain target:self action:@selector(handleBackBarButtonItem:)];
navItem.backBarButtonItem.title = @"Chapter";
Thank you in advance! 先感谢您!
I don't think you quite understand how navigation (with UINavigationController
) works in iOS. 我认为您不太了解iOS中的导航(使用UINavigationController
)如何工作。 Assuming you want animation, this is what you want: 假设您想要动画,这就是您想要的:
Set up a UINavigationController
. 设置一个UINavigationController
。 This can be done in the app's delegate (to avoid memory leakage, set an instance variable on UINavigationController *navController
: 这可以在应用程序的委托中完成(为避免内存泄漏,请在UINavigationController *navController
上设置实例变量:
navController = [[UINavigationController alloc] initWithRootViewController:A];
Note that we are adding A
as our root view controller. 请注意,我们将A
添加为根视图控制器。
Push the second view controller when needed. 在需要时推第二个视图控制器。 I assume that you are adding B.view
after a button is clicked or something. 我假设您在单击按钮或其他B.view
后添加B.view
。 In the implementation of the method that adds the second view controller, run the following code, instead of [A.view addSubview:B.view]
. 在添加第二个视图控制器的方法的实现中,运行以下代码,而不是[A.view addSubview:B.view]
。 This method should be in the first controller's .m file: 此方法应该在第一个控制器的.m文件中:
[self.navigationController pushViewController:B animated:YES];
This will also give a nice transition effect. 这也将提供良好的过渡效果。
Pop the second view controller off the stack. 将第二个视图控制器弹出堆栈。 With UINavigationController
, a pretty arrow-shaped back button is automatically included in a pushed view controller, to navigate back to the last view controller. 使用UINavigationController
,一个漂亮的箭头后退按钮会自动包含在推送的视图控制器中,以导航回最后一个视图控制器。 This means that you don't even need any code to allow backward navigation. 这意味着您甚至不需要任何代码即可允许向后导航。
That's it! 而已! Now if you need to change the title of B
's back button, do this in A
's viewDidLoad
method: 现在,如果您需要更改B
的后退按钮的标题,请在A
的viewDidLoad
方法中执行以下操作:
self.navigationItem.backBarButtonItem = customBackButtonItem;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.