你能给我解释一下管理UIViewController生命周期的正确方式吗?
特别地,我想知道如何使用初始化,ViewDidLoad, ViewWillAppear, ViewDidAppear, ViewWillDisappear, ViewDidDisappear, ViewDidUnload和Dispose方法在UIViewController类的Mono Touch。
你能给我解释一下管理UIViewController生命周期的正确方式吗?
特别地,我想知道如何使用初始化,ViewDidLoad, ViewWillAppear, ViewDidAppear, ViewWillDisappear, ViewDidDisappear, ViewDidUnload和Dispose方法在UIViewController类的Mono Touch。
当前回答
iOS 6及以后版本。新的图表如下:
其他回答
更新:ViewDidUnload在iOS 6中已弃用,因此更新了相应的答案。
UIViewController的生命周期如图所示:
使用Xamarin Native/Mono Touch的优势在于,它使用了原生api,因此它遵循与Apple文档中相同的ViewController生命周期。
让我们集中在方法上,它们负责UIViewController的生命周期:
Creation: - (void)init - (void)initWithNibName: View creation: - (BOOL)isViewLoaded - (void)loadView - (void)viewDidLoad - (UIView *)initWithFrame:(CGRect)frame - (UIView *)initWithCoder:(NSCoder *)coder Handling of view state changing: - (void)viewDidLoad - (void)viewWillAppear:(BOOL)animated - (void)viewDidAppear:(BOOL)animated - (void)viewWillDisappear:(BOOL)animated - (void)viewDidDisappear:(BOOL)animated - (void)viewDidUnload Memory warning handling: - (void)didReceiveMemoryWarning Deallocation - (void)viewDidUnload - (void)dealloc
更多信息请查看UIViewController类参考。
根据苹果的文件-开始开发iOS应用程序(Swift) -使用视图控制器-理解视图控制器生命周期
viewDidLoad()—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller. viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen viewDidAppear()—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation. viewWillDisappear()—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status. viewDidDisappear()—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.
iOS 6及以后版本。新的图表如下:
图中没有提到viewWillLayoutSubviews和viewDidLayoutSubviews方法,但是在viewWillAppear和viewDidAppear之间调用这些方法。它们可以被多次调用。