首页 > 解决方案 > Swift:我的destinationVC segue 显示为零

问题描述

我让用户通过文本字段(姓名、电子邮件等)填写一些个人资料信息,这些信息用于设置我的 ProfileContoller.shared.profile 值。当我到达导航 segue 以传递数据时,我的 destinationVC.profile 不会将其值设置为发送配置文件对象,而是得到 nil。

我的sendingVC 嵌入在导航控制器中,而我的destinationVC 嵌入在标签栏控制器中。

Segue SendingVC

属性检查器 SendingVC

目的地VC

// Sending View Controller: 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}

我的发送对象有数据:(lldb)po profile Profile:0x600000c873c0

目标对象意外为零:(lldb) po destinationVC?.profile nil

标签: swiftuistoryboardsegue

解决方案


didSet在您的 segue 中的 vc 尚未加载时触发,因此所有出口均为零

你需要放在 updateViews()里面viewDidLoad


另外你的目的地是一个tabBar

let tab = segue.destination as! UITabBarController
let destinationVC = tab.viewControllers![2] as! ProfileViewController

推荐阅读