iOS属性传值、代理传值

2015-12-03  本文已影响628人  ThEAll

import "AppDelegate.h"

import "FirstViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


import "FirstViewController.h"

import "SecondViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

// 导航条左侧按钮回调方法
-(void)endEditingAction{
[self.view endEditing:YES];
}


import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

@property (nonatomic ,retain)NSString *userStr; // 用来接受第一个界面传过来的内容
@property (nonatomic ,retain)NSString *pwsStr;
@property (nonatomic ,retain)NSString *yanZhengStr;

@end

import "SecondViewController.h"

import "ThirdViewController.h"

@interface SecondViewController ()<ThirdViewControllerDelegate>

@end

@implementation SecondViewController

// thirdVC的代理方法,作用为,将thirdVC上的值传递到当前的视图控制器
-(void)passValueWithDic:(NSDictionary *)valueDic{
NSLog(@"dic_______%@",valueDic);
UILabel userLabel = (UILabel)[self.view viewWithTag:5000];
userLabel.text = [valueDic valueForKey:@"name"];

UILabel *pswLabel = (UILabel*)[self.view viewWithTag:5001];
pswLabel.text = [valueDic valueForKey:@"pws"];

UILabel *yanZhengLabel = [self.view viewWithTag:5002];
yanZhengLabel.text = [valueDic valueForKey:@"yanZheng"];

}

// 导航条右侧按钮回调方法,点击跳转到下个界面(ThirdViewController)
-(void)rightBarButtonAction:(UIBarButtonItem*)sender{
ThirdViewController *thirdVC = [[ThirdViewController alloc]init];
// 指定代理 {self:在类方法(加号方法)中指的是本类,在对象方法(减号方法)中指的是该类的一个对象}
thirdVC.delegate = self;
[self.navigationController pushViewController:thirdVC animated:YES];
}


import <UIKit/UIKit.h>

@protocol ThirdViewControllerDelegate <NSObject>

// 该方法的参数就是要传递的值
-(void)passValueWithDic:(NSDictionary*)valueDic;

@end

@interface ThirdViewController : UIViewController

@property (nonatomic ,assign)id<ThirdViewControllerDelegate> delegate;

@end

import "ThirdViewController.h"

@interface ThirdViewController ()

@end

@implementation ThirdViewController

}
// 返回按钮的点击事件
-(void)backBtnAction:(UIBarButtonItem*)sender{
UITextField nameTextField = (UITextField)[self.view viewWithTag:1000];
UITextField pwsTextField = (UITextField)[self.view viewWithTag:1001];
UITextField yanZhengTextField = (UITextField)[self.view viewWithTag:1002];

/*
 if条件判断中
 第一步:先判断是否指定了代理
 第二步:respondsToSelector该方法的返回值为BOOL类型。该方法会从指定的代理类中(这里我们的代理类就是SecondViewController)找寻方法选择器重中方法的实现,如果没有实现该协议方法,就返回NO,如果实现,就返回YES
 self.delegate : 指定哪个类为代理,它就是代理类的一个对象,在这里它指的就是 SecondViewController这个类的一个对象那,我们在SecondViewController也实现了passValueWithDic:这个方法,所以我们可以调用此方法
 (self.delegate = SecondViewController)
      */

if (self.delegate && [self.delegate respondsToSelector:@selector(passValueWithDic:)]) {
[self.delegate passValueWithDic:@{@"name":nameTextField.text,@"pws":pwsTextField.text,@"yanZheng":yanZhengTextField.text}];
}

[self.navigationController popViewControllerAnimated:YES];

}

上一篇 下一篇

猜你喜欢

热点阅读