建立一個(gè)空項(xiàng)目, 刪除 ViewController.swift, 新建 AViewControllor.swift 和 BViewController.swift, 并在 AViewController 中嵌入導(dǎo)航控制器雨席。分別在這兩個(gè)控制器中拖入按鈕和 Label, 并進(jìn)行聯(lián)線和設(shè)置 Outlet腕铸。 選中 AViewControllor 和 BViewController 之間的聯(lián)線, 設(shè)置其 identifier 為 "AtoB"环肘。
//
// AViewController.swift
// 控制器間反向傳值
//
// Created by chenyf on 16/3/17.
// Copyright ? 2016年 chenyf. All rights reserved.
//
import UIKit
class AViewController: UIViewController, UITextFieldDelegate, SendMessageDelegate {
@IBOutlet var aTextField: UITextField!
@IBOutlet var aTextLabel: UILabel!
@IBAction func passValueToB(sender: UIButton) {
}
override func viewDidLoad() {
// 設(shè)置控制器為 UITextField 的代理
aTextField.delegate = self
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AtoB" {
// 取得 B 視圖控制器
let bController:BViewController = segue.destinationViewController as! BViewController
// A 給 B 傳值
bController.tempString = aTextField.text
bController.delegate = self // 設(shè)置代理
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
func sendValue(message: String) {
self.aTextLabel.text = message
}
}
//
// BViewController.swift
// 控制器間反向傳值
//
// Created by chenyf on 16/3/17.
// Copyright ? 2016年 chenyf. All rights reserved.
//
import UIKit
// 發(fā)送消息的協(xié)議
protocol SendMessageDelegate {
func sendValue(message: String)
}
class BViewController: UIViewController, UITextFieldDelegate {
// 代理給 A 控制器, 是為了把值傳給 A, 這兒用協(xié)議來(lái)進(jìn)行控制器之間的通信
var delegate: SendMessageDelegate?
var tempString:String?
@IBOutlet var bTextField: UITextField!
@IBOutlet var bTextLabel: UILabel!
@IBAction func passValueToA(sender: UIButton) {
if(self.delegate != nil) {
self.delegate!.sendValue(bTextField.text!)
self.navigationController?.popViewControllerAnimated(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
bTextField.delegate = self
self.bTextLabel.text = tempString
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
在 AppDelegate.swift 中:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 獲取根視圖控制器
let nav = self.window!.rootViewController as! UINavigationController
// 將 AViewController 實(shí)例設(shè)置為導(dǎo)航控制器的 topViewController
let _ = nav.topViewController as! AViewController
return true
}
Paste_Image.png
s.gif