iOS通过代理逆向传值的方式详解

2020-01-18 18:27:06丽君

四、实现步骤

分析: 现在是第二个界面想传值,但是自己做不了,所以它是被代理对象,第一个界面自然就是代理对象。然后根据上面的规范写代码。

1、被代理对象


//.h 文件

//被代理对象 做以下几件事
//1、创建一个协议,用于传值
//2、声明一个遵守上述协议的delegate属性
/**
 * 创建协议,里面有一个方法,带一个参数,该参数就是我想传出去的值
 */
@protocol passValue <NSObject>
-(void)passedValue:(NSString *)inputValue;
@end

@interface NextViewController : UIViewController
/**
 * 声明一个delegate属性
 */
@property(nonatomic, weak) id<passValue> delegate;
@end

=================================================================

//.m 文件
#import "NextViewController.h"

@interface NextViewController ()
@property (weak, nonatomic) IBOutlet UITextField *inputText;
- (IBAction)back:(id)sender;
@end

@implementation NextViewController
- (void)viewDidLoad {
 [super viewDidLoad]; 
 self.navigationItem.title = @"第二个界面";
}

/**
 * 返回上一个界面
 *
 * @param sender <#sender description#>
 */
- (IBAction)back:(id)sender {
 NSString *inputString = self.inputText.text;
 //3、调用代理对象完成传值
 if(self.delegate && [self.delegate respondsToSelector:@selector(passedValue:)]){
  [self.delegate passedValue:inputString];
 }
 [self.navigationController popViewControllerAnimated:YES];
}
@end

2、代理对象


//.h 文件

#import <UIKit/UIKit.h>
#import "NextViewController.h"
//代理对象
//实现被代理对象创建的协议,实现其中的方法,捕获传过来的值
@interface ViewController : UIViewController <passValue>
@end
=================================================================

//.m 文件
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *nextPassedValue;
- (IBAction)next:(id)sender;
@end

@implementation ViewController
- (void)viewDidLoad {
 [super viewDidLoad]; 
}

/**
 * 实现被代理对象的方法,将捕获的值设置到UILabel中
 *
 * @param inputValue 传过来的值
 */
-(void)passedValue:(NSString *)inputValue{
 self.nextPassedValue.text = inputValue;
}

//点击返回按钮跳转到第二个界面
- (IBAction)next:(id)sender { 
 NextViewController *nvc = [[NextViewController alloc]init];
 //设置被代理对象的delegate属性为代理对象即self
 nvc.delegate = self;
 [self.navigationController pushViewController:nvc animated:YES];
}
@end

五、实现效果

ios,代理逆向传值,代理传值,ios逆向传值

总结

以上就是这篇文章的全部内容了,希望本文的内容对各位iOS开发者们能有所帮助,如果有疑问大家可以留言交流。