Swift 4: prepare(for segue:) being called after viewDidLoad

喜你入骨 提交于 2020-01-13 10:37:29

问题


I have 2 VCs: CouponVC and CouponFeedbackVC.

Coupon VC receives brand: Brand! from its parentViewController. Now I want to pass the brand.name to CouponFeedbackVC.

CouponVC.swift

var brandName: String!
override func viewDidLoad() {
    super.viewDidLoad
    brandName = brand.name
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "couponToFeedBack" {
        if let vc = segue.destination as? CouponFeedbackVC {
            print(brandName)
            vc.brandName = self.brandName
        }
    }
}

In CouponFeedbackVC.swift

var brandName: String!
override func viewDidLoad() {
    super.viewDidLoad()
    print("viewDidLoad")
    print(brandName)
}

 override func awakeFromNib() {
    print(brandName)
    self.view.layoutIfNeeded()
}

Console Log

nil
viewDidLoad
nil
StayUncle

awakeFromNib() -> viewDidLoad() -> prepare(for segue:)

I am not accessing any outlets from CouponFeedbackVC.

Why is prepare(for segue: ) being called after viewDidLoad() and awakeFromNib()?


回答1:


In awakeFromNib you are referencing self.view in order to call layoutIfNeeded. This causes the view to be loaded and viewDidLoad to be called.

If you remove the call to self.view.layoutIfNeeded from awakeFromNib then viewDidLoad will not be called until after prepare(for:sender:). There is no reason to call layoutIfNeeded in awakeFromNib.




回答2:


viewDidLoad() and awakeFromNib() is called before prepare(for segue: ) because for passing data from one view controller to another you have to initialize and allocate the object So when awakeFromNib is called, it is guaranteed to have all its outlet and action connections already established and than viewDidLoad is called which give assurety the view controller has loaded its view hierarchy into memory. Now its ready for passing data from one viewcontroller to another.



来源:https://stackoverflow.com/questions/46617760/swift-4-preparefor-segue-being-called-after-viewdidload

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