I want to pass information obtained from a textfield to several view controllers, is it possible? how?
thanks
I want to pass information obtained from a textfield to several view controllers, is it possible? how?
thanks
To move from one view controller to another you can relate them by a segue way, in this way you can pass information from one view controller to another.
Let's say you have a MyViewController1 and you want to pass information to MyViewController2
class MyViewController1: UIViewController {
var infoPrueba: String!
override func viewDidLoad() {
super.viewDidLoad()
//Asignamos algún valor a la variable que deseamos
infoPrueba = "Esta es una info"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
//Obtenemos la referencia del siguiente view controller
let controller2 = segue.destination as! MyViewController2
//Aqui pasas la variable de información al siguiente view controller
controller2.infoDeViewController1 = infoPrueba
}
}
}
class MyViewController2: UIViewController {
var infoDeViewController1: String!
override func viewDidLoad() {
super.viewDidLoad()
//En este punto la variable debe contener la información del
anterior view controller
print(infoDeViewController1)
}
}
There are several ways to share information in different controllers, which one you use depends on what you need. The most common options are:
Create a global class
class Global {
static let sharedInstance = Global()
var anyVariable: String
}
In any class you access the value: Global.sharedInstance.anyVariable
By NotificationCenter (Special care), this method is used in particular to send notifications from a class, and that these are received by anyone else who wants to subscribe to it. the data can be sent within the userInfo object of the notification
Clase A Emitirá la notificación
let nc = NotificationCenter.default
nc.post(name:Notification.Name(rawValue:"Cambiounvalor"),object: nil, userInfo: ["valor":1])
Clase B Recibirá la notificación
let myNotification = Notification.Name(rawValue: "Cambiounvalor")
let nc = NotificationCenter.default
nc.addObserver(forName:myNotification, object:nil, queue:nil, using:metodoqueseejecuta)
func metodoqueseejecuta(notification:Notification) -> Void {
guard let index = notification.userInfo?["valor"] as? Int
}
Delegates and Protocols