欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

ViewController LifeCycle

程序员文章站 2024-01-30 20:21:46
we will focused on the differences between viewDidLoad, viewDidAppear, and viewDidLayoutSubviews.The definition given by Apple on viewDidLoad mentioned that it is called after the controller’s view is loaded into memory. To put it in a simple term, it is...

we will focused on the differences between viewDidLoad, viewDidAppear, and viewDidLayoutSubviews.

The definition given by Apple on viewDidLoad mentioned that it is called after the controller’s view is loaded into memory. To put it in a simple term, it is the first method that will load.
for instance:

override func viewDidLoad() {
  super.viewDidLoad()
  view.backgroundColor = UIColor.blue //so the first thing will be 
}

viewDidAppear: Apple defines this as ‘notifies the view controller that its view was added to a view hierarchy. In another word, it basically means that this is being called when the screen is shown to the user.

override func viewDidAppear() {
  super.viewWillAppear(animated) //show the animate of view appears
}

or in a more complicated example:

override func viewDidAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  imageView.center.x = self.view.frame.width + 300
  let center = slef.view.frame.width / 2
  UIView.animate(withDuration: 0.5) {
  slef.imageView.center.x = center
  self.image.image = UIImage(named: "image")
}

The difference between viewDidAppear and viewDidLoad is that viewDidAppear is called every time you land on the screen while viewDidLoad is only called once which is when the app loads.

then, what is viewDidLayoutSubview?

viewDidLayoutSubviews is called every time the view is updated, rotated or changed or it’s bounds change. The keyword here is bounds change.
which means, it define the change of this view when we rotate our phone.
and keep in mind:
viewDidLayoutSubviews will always override viewDidLoad.

for example:

ViewController LifeCycle

1 This will print out the initial position of the button
2 This will replace the initial position with a new position

本文地址:https://blog.csdn.net/weixin_44337445/article/details/107147796