Свифт: моя цель - PullRequest
       14

Свифт: моя цель

0 голосов
/ 30 мая 2019

У меня есть пользователи, которые заполняют некоторую информацию профиля через текстовые поля (имя, адрес электронной почты и т. Д.), Которые используются для установки значений моего ProfileContoller.shared.profile.Когда я добираюсь до своей навигации, чтобы передать данные, мой destinationVC.profile не установит его значение для объекта профиля отправки, и вместо этого я получу nil.

Мой sendVC встроен в контроллер навигации, в то время как мойdestinationVC встроен в контроллер панели вкладок.

Segue SendingVC

Инспектор атрибутов SendingVC

DestinationVC

// 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 Профиль: 0x600000c873c0

Объект назначения неожиданно равен nil: (lldb) po destinationVC? .Profile nil

Ответы [ 3 ]

0 голосов
/ 30 мая 2019

Я думаю, все, что вам нужно сделать, это вызвать updateViews() в главном потоке.

didSet {
        print("did set profile called")
        DispatchQueue.main.async{[weak self] in
            guard let self = self else {
                return
            }
            self.updateViews()
        }
    }

Другой вариант - обновить представления в viewDidLoad()

override func viewDidLoad() {
    if let prof = self.profile {
        self.updateViews()
    }
}
0 голосов
/ 30 мая 2019

Вы можете использовать приведенный ниже код для безопасной передачи данных в ProfileViewController.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let profile = ProfileController.shared.profile else { return }
        if segue.identifier == "signUpMemicTBC" {
            guard let tabBarController = segue.destination as? UITabBarController else { return }
            guard let profileController = tabBarController.viewControllers?.index(at: 2) as? ProfileViewController else {
                return
            }
            profileController.profile = profile
        }
    }
0 голосов
/ 30 мая 2019

didSet срабатывает, пока ваш vc в segue еще не загружен, поэтому все выходы равны нулю

нужно положить updateViews() внутрь viewDidLoad


Плюс пункт назначения - это tabBar

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