最近在看传递数据的方面,从主界面到第二个界面时,可以用segue 和 import 一下就行,不过从 第二个界面到第一个界面,貌似这两种方法都不可行,所以可以用协议的方法来做
swift版
先定义一个协议
import Foundation
protocol Send{
func Send(value:String)
}
然后在发送数据的view controller里面定义delegate的类型为send,不用添加协议,
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
}
}
OC版本的实际上和swift版本的差不多
首先定义一个协议
#import <Foundation/Foundation.h>
@protocol PassValueDelegate <NSObject>
-(void)passValue:(int)value;
@end
随后在发送方定义delegate 记住一定要在.h文件中定义,否则在接收方里识别不出这个delegate
@property NSObject<PassValueDelegate>*delegate;
随后在.m文件中实现传输的方法
- (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
这个博客写的蛮好的