本文介绍了Swift 4:在 viewDidLoad 之后调用 prepare(for segue:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个 VC:CouponVCCouponFeedbackVC.

I have 2 VCs: CouponVC and CouponFeedbackVC.

Coupon VC 从其 parentViewController 接收 brand: Brand!.现在我想将 brand.name 传递给 CouponFeedbackVC.

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

CouponVC.swift

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
        }
    }
}

在 CouponFeedbackVC.swift 中

In CouponFeedbackVC.swift

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

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

控制台日志

nil
viewDidLoad
nil
StayUncle

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

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

我没有从 CouponFeedbackVC 访问任何网点.

I am not accessing any outlets from CouponFeedbackVC.

为什么在 viewDidLoad()awakeFromNib() 之后调用 prepare(for segue: )?

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

推荐答案

awakeFromNib 中,您正在引用 self.view 以调用 layoutIfNeeded>.这会导致加载视图并调用 viewDidLoad.

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

如果您从 awakeFromNib 中删除对 self.view.layoutIfNeeded 的调用,则 viewDidLoad 将在 prepare(for:sender:).没有理由在 awakeFromNib 中调用 layoutIfNeeded.

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.

这篇关于Swift 4:在 viewDidLoad 之后调用 prepare(for segue:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:16