最近在看传递数据的方面,从主界面到第二个界面时,可以用segue 和 import 一下就行,不过从 第二个界面到第一个界面,貌似这两种方法都不可行,所以可以用协议的方法来做
swift版
先定义一个协议
import Foundation protocol Send{ func Send(value:String) }
var delegate:Send?
@IBAction func cao(sender: UIButton) { self.delegate?.Send("\(100)") }这个关联一个按钮的动作,表示传输数据
整体的first view controller 的代码如下
import UIKit class FirstViewController: UIViewController{ var delegate:Send? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cao(sender: UIButton) { self.delegate?.Send("\(100)") }
随后在接受的view controller里卖弄添加协议的委托方为自己,在这里要导入协议
@IBAction func change(sender: UIButton) { let vc = FirstViewController() vc.delegate = self self.navigationController!.pushViewController(vc, animated: true) } func Send(value: String) { label.text = value } }
import UIKit class ViewController: UIViewController,Send{ @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func change(sender: UIButton) { let vc = FirstViewController() vc.delegate = self self.navigationController!.pushViewController(vc, animated: true) } func Send(value: String) { label.text = value } }
首先定义一个协议
#import <Foundation/Foundation.h> @protocol PassValueDelegate <NSObject> -(void)passValue:(int)value; @end
@property NSObject<PassValueDelegate>*delegate;
- (IBAction)back:(UIButton *)sender { [self.delegate passValue:self.b]; [self.navigationController popToRootViewControllerAnimated:true]; }
First.delegate = self;
-(void)passValue:(int)value{ temp = value; NSLog(@"%d",temp); self.label.text = [NSString stringWithFormat:@"%d",temp]; }
http://blog.csdn.net/ryantang03/article/details/7915045
这个博客写的蛮好的