Элемент экземпляра нельзя использовать для типа при нажатии UIViewController - PullRequest
0 голосов
/ 06 февраля 2019

Я программно настраиваю ViewControllers (без раскадровки).

Я хочу передать данные следующему VC, и хотя я знаю, как это сделать с помощью перехода и раскадровки, я не могу понять,о том, как сделать это чисто программно.

Я получаю сообщение об ошибке «Не удается использовать элемент экземпляра для типа ...»

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

CarbonCalculatorResultsViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

Нужно ли создавать экземпляр следующего VC, прежде чем я смогупередать данные?Вот о чем этот ответ говорит о пока у меня нет раскадровки.Спасибо!

Ответы [ 3 ]

0 голосов
/ 06 февраля 2019

Текущий пример кода (см. Выше) устанавливает значение статической переменной (принадлежит CarbonCalculatorResultsViewController.Type.

. Я полагаю, что вы хотите реализовать следующее:

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

nextViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

Этот пример кода устанавливает значение переменной экземпляра userInformation для типа nextViewController.

0 голосов
/ 06 февраля 2019

Шаг 1: Установите класс назначения

В CarbonCalculatorResultsViewController классе объявите var для получения таких данных:

class CarbonCalculatorResultsViewController: UIViewController {
    var foo: String? {
        didSet {
            // What you'd like to do with the data received
            print(foo ?? "")
        }
    }

    ovevride func viewDidLoad() {
       //
    }
}

Шаг 2: Подготовьте данные в вашем исходном классе

let nextViewController = CarbonCalculatorResultsViewController()
// You have access of the variable in CarbonCalculatorResultsViewController
nextViewController.foo = <data_you_want_to_pass>

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

Затем, каждый раз, когда CarbonCalculatorResultsViewController оживает, вызывается didSet{} из foo.

0 голосов
/ 06 февраля 2019

Вы должны передать переменную в Object, а не в Class

Заменить: CarbonCalculatorResultsViewController.userInformation = userInformation

На: nextViewController.userInformation = userInformation

Примечание:

CarbonCalculatorResultsViewController - это Class.

nextViewController - это Object.

Ваш полный код должен выглядеть следующим образом:

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller.  There is already a variable in that file: var userInformation: UserInformation?

nextViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)
...