问题
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