Swift 傳值之通知傳值

通知傳值記住使用完通知時移除通知,工程建立和屬性,代理,閉包傳值一樣

屬性傳值:http://blog.csdn.net/zhangjitao_boke/article/details/50606185

代理傳值:http://blog.csdn.net/zhangjitao_boke/article/details/50606707

閉包傳值:http://blog.csdn.net/zhangjitao_boke/article/details/50607325

單例傳值:http://blog.csdn.net/zhangjitao_boke/article/details/50608066


代碼 

FirstViewController


//
// FirstViewController.swift
// NotificationPassValue
//
// Created by JT on 16/1/29.
// Copyright © 2016年 JT. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController {

@IBOutlet weak var firstTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
}

// 收到通知post後執行方法
func getValue(notification:NSNotification) {
// 賦值
firstTextField.text = notification.object as? String
// 移除通知
NSNotificationCenter.defaultCenter().removeObserver(self, name: "passValue", object: nil)
}


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 添加通知
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "getValue:", name: "passValue", object: nil)


let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let secondVC = storyBoard.instantiateViewControllerWithIdentifier("secondVC")
self.navigationController?.pushViewController(secondVC, animated: true)
}


}

SecondViewController 代碼:

//
// SecondViewController.swift
// NotificationPassValue
//
// Created by JT on 16/1/29.
// Copyright © 2016年 JT. All rights reserved.
//

import UIKit

class SecondViewController: UIViewController {

@IBOutlet weak var secondTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()

self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backAction")

}
func backAction() {
// 發送通知
let center = NSNotificationCenter.defaultCenter()
center.postNotificationName("passValue", object: secondTextField.text!)

self.navigationController?.popViewControllerAnimated(true)
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章