Cepat 5
Yah Matt Price's Answer baik-baik saja untuk meneruskan data tetapi saya akan menulis ulang, dalam versi Swift Terbaru karena saya percaya programmer baru menemukan itu berhenti menantang karena Sintaks dan metode / kerangka kerja baru, seperti posting asli di Objective-C.
Ada beberapa opsi untuk Passing Data antara View Controllers.
- Menggunakan Push Pengontrol Navigasi
- Menggunakan Segue
- Menggunakan Delegasi
- Menggunakan Pengamat Notifikasi
- Menggunakan Blok
Saya akan menulis ulang logikanya dalam Swift dengan Kerangka iOS terbaru
Melewati Data melalui Push Pengontrol Navigasi : Dari ViewControllerA ke ViewControllerB
Langkah 1. Deklarasikan variabel di ViewControllerB
var isSomethingEnabled = false
Langkah 2. Cetak Variabel dalam metode ViewDidLoad ViewControllerB
override func viewDidLoad() {
super.viewDidLoad()
//Print value received through segue, navigation push
print("Value of 'isSomethingEnabled' from ViewControllerA : ", isSomethingEnabled)
}
Langkah 3. Di ViewControllerA Lulus Data sambil mendorong melalui Pengontrol Navigasi
if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
viewControllerB.isSomethingEnabled = true
if let navigator = navigationController {
navigator.pushViewController(viewControllerB, animated: true)
}
}
Jadi di sini adalah kode lengkap untuk:
ViewControllerA
import UIKit
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK:Passing Data through Navigation PushViewController
@IBAction func goToViewControllerB(_ sender: Any) {
if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
viewControllerB.isSomethingEnabled = true
if let navigator = navigationController {
navigator.pushViewController(viewControllerB, animated: true)
}
}
}
}
ViewControllerB
import UIKit
class ViewControllerB: UIViewController {
//MARK: - Variable for Passing Data through Navigation push
var isSomethingEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
//Print value received through navigation push
print("Value of 'isSomethingEnabled' from ViewControllerA : ", isSomethingEnabled)
}
}
Melewati Data melalui Segue : Dari ViewControllerA ke ViewControllerB
Langkah 1. Buat Segue dari ViewControllerA ke ViewControllerB dan berikan Identifier = showDetailSegue di Storyboard seperti yang ditunjukkan di bawah ini
Langkah 2. Di ViewControllerB Deklarasikan yang layak bernama isSomethingEnabled dan cetak nilainya.
Langkah 3. Di PassControllerA pass adalah nilai sesuatuSomethingEnabled saat melewati Segue
Jadi di sini adalah kode lengkap untuk:
ViewControllerA
import UIKit
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - - Passing Data through Segue - -
@IBAction func goToViewControllerBUsingSegue(_ sender: Any) {
performSegue(withIdentifier: "showDetailSegue", sender: nil)
}
//Segue Delegate Method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showDetailSegue") {
let controller = segue.destination as? ViewControllerB
controller?.isSomethingEnabled = true//passing data
}
}
}
ViewControllerB
import UIKit
class ViewControllerB: UIViewController {
var isSomethingEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
//Print value received through segue
print("Value of 'isSomethingEnabled' from ViewControllerA : ", isSomethingEnabled)
}
}
Melewati Data melalui Delegasi : Dari ViewControllerB ke ViewControllerA
Langkah 1. Deklarasikan Protokol ViewControllerBDelegate dalam file ViewControllerB tetapi di luar kelas
protocol ViewControllerBDelegate: NSObjectProtocol {
// Classes that adopt this protocol MUST define
// this method -- and hopefully do something in
// that definition.
func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?)
}
Langkah 2. Mendeklarasikan instance variabel Delegasi di ViewControllerB
var delegate: ViewControllerBDelegate?
Langkah 3. Kirim data untuk didelegasikan di dalam metode viewDidLoad dari ViewControllerB
delegate?.addItemViewController(self, didFinishEnteringItem: "Data for ViewControllerA")
Langkah 4. Konfirmasikan ViewControllerBDelegate di ViewControllerA
class ViewControllerA: UIViewController, ViewControllerBDelegate {
// to do
}
Langkah 5. Konfirmasikan bahwa Anda akan menerapkan delegasi di ViewControllerA
if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
viewControllerB.delegate = self//confirming delegate
if let navigator = navigationController {
navigator.pushViewController(viewControllerB, animated: true)
}
}
Langkah 6. Terapkan metode delegasi untuk menerima data di ViewControllerA
func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?) {
print("Value from ViewControllerB's Delegate", item!)
}
Jadi di sini adalah kode lengkap untuk:
ViewControllerA
import UIKit
class ViewControllerA: UIViewController, ViewControllerBDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
//Delegate method
func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?) {
print("Value from ViewControllerB's Delegate", item!)
}
@IBAction func goToViewControllerForDelegate(_ sender: Any) {
if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
viewControllerB.delegate = self
if let navigator = navigationController {
navigator.pushViewController(viewControllerB, animated: true)
}
}
}
}
ViewControllerB
import UIKit
//Protocol decleare
protocol ViewControllerBDelegate: NSObjectProtocol {
// Classes that adopt this protocol MUST define
// this method -- and hopefully do something in
// that definition.
func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?)
}
class ViewControllerB: UIViewController {
var delegate: ViewControllerBDelegate?
override func viewDidLoad() {
super.viewDidLoad()
//MARK: - - - - Set Data for Passing Data through Delegate - - - - - -
delegate?.addItemViewController(self, didFinishEnteringItem: "Data for ViewControllerA")
}
}
Melewati Data melalui Pengamat Pemberitahuan : Dari ViewControllerB ke ViewControllerA
Langkah 1. Setel dan Posting data dalam Pengamat pemberitahuan di ViewControllerB
let objToBeSent = "Test Message from Notification"
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)
Langkah 2. Tambahkan Pengamat Pemberitahuan di ViewControllerA
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Langkah 3. Terima nilai data Notifikasi di ViewControllerA
@objc func methodOfReceivedNotification(notification: Notification) {
print("Value of notification : ", notification.object ?? "")
}
Jadi di sini adalah kode lengkap untuk:
ViewControllerA
import UIKit
class ViewControllerA: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// add observer in controller(s) where you want to receive data
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
}
//MARK: Method for receiving Data through Post Notification
@objc func methodOfReceivedNotification(notification: Notification) {
print("Value of notification : ", notification.object ?? "")
}
}
ViewControllerB
import UIKit
class ViewControllerB: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//MARK:Set data for Passing Data through Post Notification
let objToBeSent = "Test Message from Notification"
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)
}
}
Melewati Data melalui Blok : Dari ViewControllerB ke ViewControllerA
Langkah 1. Deklarasikan blok di ViewControllerB
var authorizationCompletionBlock: ((Bool) -> ())? = {_ in}
Langkah 2. Atur data dalam blok di ViewControllerB
if authorizationCompletionBlock != nil
{
authorizationCompletionBlock!(true)
}
Langkah 3. Terima data blok di ViewControllerA
//Receiver Block
controller!.authorizationCompletionBlock = { isGranted in
print("Data received from Block is :", isGranted)
}
Jadi di sini adalah kode lengkap untuk:
ViewControllerA
import UIKit
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK:Method for receiving Data through Block
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showDetailSegue") {
let controller = segue.destination as? ViewControllerB
controller?.isSomethingEnabled = true
//Receiver Block
controller!.authorizationCompletionBlock = { isGranted in
print("Data received from Block is :", isGranted)
}
}
}
}
ViewControllerB
import UIKit
class ViewControllerB: UIViewController {
//MARK:Variable for Passing Data through Block
var authorizationCompletionBlock:((Bool)->())? = {_ in}
override func viewDidLoad() {
super.viewDidLoad()
//MARK:Set data for Passing Data through Block
if authorizationCompletionBlock != nil
{
authorizationCompletionBlock!(true)
}
}
}
Anda dapat menemukan contoh aplikasi lengkap di GitHub saya. Mohon beri tahu saya jika ada pertanyaan tentang ini.
@class ViewControllerB;
definisi @protocol di atas? Tanpa itu saya mendapatkan kesalahan "Diharapkan jenis" pada ViewControllerB di baris:- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
dalam@protocol
deklarasi