本節學習內容:
1.多界面傳值的基本概念
2.多界面傳值的方法
3.多界面傳值的應用
【多界面傳值 屬性】
changeColor:改變顏色協義函數
delegate:代理對象設計
assign:代理賦值類型
1.創建三視圖分別為VCFirst,VCSecond,VCThird,都繼承于UIViewController
【VCFIrst.m】
#import"VCFirst.h"
#import"VCSencend.h"
@interface VCFirst()
@end
@implementation VCFirst
-(void)viewDidLoad{
[super viewDidLoad];
}
//點擊時推出視圖控制器二
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
VCSecond* vc=[[VCSecond alloc]init];
vc.view.backgroundColor=[UIColor orangeColor];
//推出視圖控制器二
[self.navigationController pushViewController:vc animated:YES];
}
【VCSecond.h】
//定義代理協義,視圖控制器二的協義
@protocol VCSecondDelegate<NSObject>
//定義一個協義函數,改變背景顏色
-(void) changColor:(UIColor*)color;
@end
@interface VCSecond:UIViewController
@property(assign,nonatomic)NSInteger tag;
//定義一個代理對象,代理對象會執行協議函數,通過代理對象實現協義函數,達到代理對象改變本身屬性的目的,代理對象一定要實現代理協義
@property(assign,nonatomic)id<VCSecondDelegate>delegate;
@end
【VCSecond.m】
#import"VCSecond.h"
@interface VCSecond()
@end
@implementation VCSecond
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor=[UIColor purpleColor];
//必變顏色導般欄按鈕
UIBarButtonItem* btnChange=[UIBarButonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(pressChange)];
self.navigationItem.rightBarButtonItem=btnChange;
}
//點擊按鈕觸發代理事件
-(void) pressChange{
//代理對象調用事件函數
_delegate changeColor:[UIColor redColor]];]
}
【VCFirst.h】
#import<UIKit/UIKit.h>
#import"VCSecond.h"
//繼承 VCSecondDelegate代理
@interface VCFirst:UIViewController<VCSecondDelegate>
-(void)changeColor:(UIColor *)color;
@end
【VCFirst.m】
#import"VCFirst.h"
@inteface VCFirst()
@end
@implementation VCFirst
-(void)viewdidLoad{
[super viewdidLoad];
}
-(void)chanteColor:(UIColor *)color{
self.view.backgroundColor=color;
}
//推出視圖控制器二
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
VCSecond* vc=[[VCSecond alloc]init];
//將當前的控制器做為代理對象賦值
vc.delegate=self;
//推出視圖控制器二
[self.navigationController pushViewController:vc animated:YES];
}
【Delegate.m】
#import"AppDelegate.h"
#import"VCFirst.h"
#import"VCThird.h"
@interface AppDelegate()
@end
@implementation AppDelegate
-(BOOL)application:(UIApplication *)application didFinshLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window=[[UIwindow alloc]initWithFrame:[UIScreen mainScreen]..bouns]
[self.window makeKeyAndVisible];
VCFirst* vcFirst=[[VCFirst alloc]init];
vcFirst* vcFirst=[[VCFirst alloc]init];
vcFirst.title=@"視圖一";
vcFirst.view.backgroundColor=[UIColor whiteColor];
//加載到導航控制器
UINavigationController* nav=[[UINavigationController alloc]initWithRootViewController:vcFirst];
VCThird* vcThird=[[VCThird alloc]init];
VCThird.title=@"視圖三";
vcThird.view.backgroundColor=[UIClolor greenColor];
NSArray* array=[NSArray arrayWithObjects:nav,vcThird,nil];
//分欄視圖控制器
UITablBarController* tabVC=[[UITabBarController alloc]init];
tabVC.viewControllers=array;
self.window.rootViewController=tabVC;
return YES;
}