F
F
FlooDwm2016-11-15 23:55:47
iOS
FlooDwm, 2016-11-15 23:55:47

Pass data between controllers programmatically?

There are HomeViewController and NextViewController how to pass a variable from the first to the second without using storyboard and segue (and how back from the second to the first), the variable must be passed before loading viewDidLoad()
The transition is done like this

func handleSearch(){
        navigationController?.pushViewController(AlfavitController(), animated: true)
    }

User Default, Data Core do not offer.
If possible, then with an example, and not just an answer like (use delegates, read about singleton)
THANK YOU IN EARLY TO EVERYONE WHO HELP!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iMike, 2017-02-14
@FlooDwm

If you use a storyboard, then you can pass data through prepareForSegue
Let's say you have a NextViewController with a variable name: String

class NextViewController: UIViewController {
    var name: String!
}

and you need to pass a name to it, then in prepareForSegue there are two ways to detect the transition to the NextViewController:
1. If we have only one transition to the NextViewController or there are many of them from different buttons, but the data is always the same
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let dest = segue.destination as? NextViewController {
        dest.name = "Jessica"
    }
}

2. If we have different transitions to NextViewController and the set of transmitted data is different
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let dest = segue.destination as? NextViewController {
        if segue.identifier == "action1" {
            dest.name = "Jessica"
        } else if segue.identifier == "action2" {
            dest.name = "Jessica"
            dest.sex = "female"
        }
    }
}

If you programmatically create a transition, then everything is even simpler. Again, two options on how to reach the NextViewController:
1. It is on the storyboard
2. Or he's not on the storyboard...
Then we attach the data
And two options for how to open the NextViewController:
1. If there is a navigationController
2. Just a modal window
dest.modalPresentationStyle = .fullScreen
dest.modalTransitionStyle = .coverVertical
present(dest, animated: true, completion: nil)

To transfer data back from the second to the first, you can use delegate or notifications.
If the delegates
protocol NextViewControllerDelegate {
    func callback(_ someString: String)
}

class NextViewController: UIViewController {
    var name: String!
    var delegate: NextViewControllerDelegate?

    func someMethod() {
        delegate?. callback("delegate callback")
    }
}

//Тут контроллер из которого открываем CustomViewController, нам помимо name нужно теперь еще задать delegate=self

class HomeViewController: UIViewController, NextViewControllerDelegate {
   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? NextViewController {
            dest.name = "Jessica"
            dest.delegate = self
        }
    }

    //MARK: NextViewControllerDelegate
    func callback(_ someString: String) {
        print("got callback with string: \(someString)")
    }
}

If notifications
let kNotifNextViewControllerCallback = NSNotification.Name(rawValue: "kNotifNextViewControllerCallback")

class NextViewController: UIViewController {
    var name: String!

    func someMethod() {
        NotificationCenter.default.post(name: kNotifNextViewControllerCallback, object: "notification text")
    }
}

//Тут HomeViewController из которого открываем CustomViewController, мы в нем будем слушать kNotifNextViewControllerCallback в метод gotNotification

class HomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(gotNotification(notification:)), name: kNotifNextViewControllerCallback, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? NextViewController {
            dest.name = "Jessica"
        }
    }

    //MARK: Notification observer
    func gotNotification(notification: Notification) {
        print("got notification with object: \(notification.object)")
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question