提要:app
起始視圖 | ListTableViewController |
目標視圖 | DetailViewController |
segue-identifier | toDetailViewide |
1.在故事板用拖拽法鏈接起始視圖和目標視圖,類型選「show」,而且設置segue的identifier。函數
2.正向傳值:spa
利用函數,prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)傳值:code
import UIKit import Alamofire import SwiftyJSON class ListTableViewController: UITableViewController { // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //根據segue的identifier有目的地傳值 if segue.identifier == "toDetailView" { if let detailView: DetailViewController = segue.destinationViewController as? DetailViewController { let data = self.noteList[self.index!] detailView.noteTitle = data["title"] as? String //這是反向傳值,告訴編譯器,DetailViewController的delegate在LisetTableViewContrliier實現 detailView.delegate = self } } } } extension ListTableViewController: SendNoticeToListView { //實現DetailViewController中的協議的函數 func sendNotice(sender: Bool) { if sender { print("我來自detailView") } } }
import UIKit import Alamofire import SwiftyJSON //定義反向傳值的協議 protocol SendNoticeToListView{ func sendNotice(sender: Bool) } class DetailViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { //用於接收傳過來的正向傳過來的值 var noteTitle: String? var delegate: SendNoticeToListView? override func viewDidLoad() { super.viewDidLoad() self.titleText.text = self.noteTitle //設置返回按鈕以及他觸發的事件 let leftBarBtn = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(backToList)) self.navigationItem.leftBarButtonItem = leftBarBtn } func backToList(){ if self.delegate != nil { //實現給協議的函數傳值 self.delegate?.sendNotice(true) //彈棧返回ListTableViewController self.navigationController?.popViewControllerAnimated(true) } } }
總結:繼承
正向傳值:事件
1.拖拽法鏈接 起始視圖和目標視圖;ci
2.設置segue的identifier;get
3.用prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)函數傳值。編譯器
反向傳值:
1.在目標視圖中:
1.1 定義用於反向傳值的協議和協議中相應的函數;
1.2 定義delegate變量,它類型是1.1的協議名;
1.3 使用delegate,調用協議中的函數,給函數的參數列表添上要反向傳遞的值,不須要實現函數
2.在起始視圖中:
2.1 繼承協議
2.2 要告訴編譯器 協議在起始視圖中實現:slef.目標視圖.delegate = self (根據實際狀況寫法不一)