Objective-C
这里演示反向传值
SecondVC.h
@protocol sendValueDelegate <NSObject>
- (void)sendValueString:(NSString *)str;
@end
@interface OC_SecController : UIViewController
@property (nonatomic,assign) id<sendValueDelegate> delegate;
SecondVC.m
// 跳转方法中
- (void)clickBack:(UIButton *)button
{
if (self.delegate && [self.delegate respondsToSelector:@selector(sendValueString:)]) {
// i am a String 是传过去的字符串
[self.delegate sendValueString:@"i am a String"];
}
[self dismissModalViewControllerAnimated:YES];
}
RootVC.m
- (void)click:(UIButton *)button
{
OC_SecController *sec = [[OC_SecController alloc] init];
// 指定代理人
sec.delegate = self;
[self presentViewController:sec animated:YES completion:^{
}];
}
// 实现代理方法
- (void)sendValueString:(NSString *)str
{
// str 就是传过来的值
NSLog(@"string : %@",str);
}
Swift
Swift 版本 我单独创建了一份协议
commond+ n
Protrol.swift
// 定义一个协议
protocol ModeViewControlDelegate{
// 协议方法
func changeLabelString(newString: String)
}
SecondVC.swift
var delegate : ModeViewControlDelegate?
// 跳转返回的点击事件
func click()->Void{
let str = textField.text
self.delegate?.changeLabelString(str!)
self.dismissViewControllerAnimated(true) { () -> Void in
}
}
RootVc.swift
// 实现协议中的方法
func changeLabelString(newString: String) {
label.text = "labeltext:\(newString)"
print(newString) // newString 从secondVC.swift 传过来的值
}
// 跳转的点击方法
func click()->Void
{
print("-------")
let sec = SecViewController();
sec.delegate = self
self.presentViewController(sec,animated: true) { () -> Void in
}
}
demo: https://github.com/Zhangjingwang1993/SwiftProtocol Swift / OC 进阶群: 498143780