iOS基礎(chǔ)控件UINavigationController中的傳值,代理傳值,正向傳值,反向傳值
#import <UIKit/UIKit.h>//聲明一個(gè)協(xié)議@PRotocol SendValue<NSObject>//定義一個(gè)方法- (void)sendBtnTitle:(NSString *)title;@end@interface FirstViewController : UIViewController// 定義代理@property (nonatomic, assign) id <SendValue>delegate;// 創(chuàng)建一個(gè)正向傳值的屬性@property (nonatomic,copy) NSString *currentTitle;@end
- (void)didButton{ NSArray *btntitles = [NSArray arrayWithObjects:@"按鍵一",@"按鍵二",@"按鍵三", nil]; for (int i=0; i<btntitles.count; i++) { UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; //改變按鍵字體顏色 [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn setTitle:[btntitles objectAtIndex:i] forState:UIControlStateNormal];
// 如果按鈕的標(biāo)題和屬性中的 _currentTitle 相同,即和根頁面中的導(dǎo)航條的 title 一樣 if([_currentTitle isEqualToString:btn.currentTitle]){
//開啟選中狀態(tài) btn.selected = YES; btn.tintColor = [UIColor whiteColor]; } [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected]; [btn addTarget:self action:@selector(titlebtnClicked:) forControlEvents:UIControlEventTouchUpInside]; btn.frame = CGRectMake(80, 140+60*i, self.view.frame.size.width-160, 40); btn.backgroundColor = [UIColor whiteColor]; [self.view addSubview:btn]; }}- (void)titlebtnClicked:(UIButton *)btn{ NSString *title = btn.currentTitle;
// 判斷代理中是否有 sendBtnTitle :這個(gè)函數(shù)
if ([_delegate respondsToSelector:@selector(sendBtnTitle:)]){
// 代理 執(zhí)行自己的 sendBtnTitle 函數(shù),傳參是 title
[_delegate sendBtnTitle:title];
}
NSLog(@"%@",title); [self.navigationController popViewControllerAnimated:YES]; }
#import <UIKit/UIKit.h>#define C(a,b,c,d) [UIColor colorWithRed:a/255.0 green:b/255.0 blue:c/255.0 alpha:d/255.0]#define IMG(name) [UIImage imageNamed:name]#import "FirstViewController.h"//將協(xié)議掛過來@interface rootViewController : UIViewController<SendValue>@end
- (void)btnClicked{ FirstViewController *first = [[FirstViewController alloc] init]; //將當(dāng)前頁面的navigationItem.title傳遞進(jìn)去 //正向傳值 first.currentTitle = self.navigationItem.title; //將代理指定為當(dāng)前rootViewController類的指針 first.delegate = self; [self.navigationController pushViewController:first animated:YES];}//實(shí)現(xiàn)協(xié)議定義的方法- (void)sendBtnTitle:(NSString *)title{ self.navigationItem.title = title;}
頁面?zhèn)髦担?/p>
正向傳值利用是屬性傳值;
反向傳值利用代理傳值;
屬性傳值:如果從A頁面往B頁面?zhèn)髦担贐頁面中聲明屬性,在A頁面中跳轉(zhuǎn)事件中給B頁面的屬性賦值;
從后一個(gè)頁面返回前一個(gè)頁面不會(huì)執(zhí)行前面頁面的loadView和viewDidLoad方法,而是執(zhí)行viewWillAppear方法,因?yàn)椋琹oadView和viewDidLoad方法的作用是將視圖加載到內(nèi)存,而從后一個(gè)頁面返回時(shí),前一個(gè)頁面已經(jīng)加載到內(nèi)存,所以不用再次加載,所以不執(zhí)行l(wèi)oadView和ViewDidLoad方法;
代理傳值:和代理設(shè)計(jì)模式一樣,按照設(shè)置代理,遵循協(xié)議的那四步來就行,
/*
1,定義協(xié)議 (BaoMuProtocol)
2,遵循協(xié)議的類 (Nurse)
3.定義需要代理的類 (Mother)
4.建立關(guān)系 (Mother中定義一個(gè)代理類型的成員變量)
*/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注