iOS基礎控件UINavigationController中的傳值,代理傳值,正向傳值,反向傳值
#import <UIKit/UIKit.h>//聲明一個協議@PRotocol SendValue<NSObject>//定義一個方法- (void)sendBtnTitle:(NSString *)title;@end@interface FirstViewController : UIViewController// 定義代理@property (nonatomic, assign) id <SendValue>delegate;// 創建一個正向傳值的屬性@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];
// 如果按鈕的標題和屬性中的 _currentTitle 相同,即和根頁面中的導航條的 title 一樣 if([_currentTitle isEqualToString:btn.currentTitle]){
//開啟選中狀態 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 :這個函數
if ([_delegate respondsToSelector:@selector(sendBtnTitle:)]){
// 代理 執行自己的 sendBtnTitle 函數,傳參是 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"//將協議掛過來@interface rootViewController : UIViewController<SendValue>@end
- (void)btnClicked{ FirstViewController *first = [[FirstViewController alloc] init]; //將當前頁面的navigationItem.title傳遞進去 //正向傳值 first.currentTitle = self.navigationItem.title; //將代理指定為當前rootViewController類的指針 first.delegate = self; [self.navigationController pushViewController:first animated:YES];}//實現協議定義的方法- (void)sendBtnTitle:(NSString *)title{ self.navigationItem.title = title;}
頁面傳值:
正向傳值利用是屬性傳值;
反向傳值利用代理傳值;
屬性傳值:如果從A頁面往B頁面傳值,在B頁面中聲明屬性,在A頁面中跳轉事件中給B頁面的屬性賦值;
從后一個頁面返回前一個頁面不會執行前面頁面的loadView和viewDidLoad方法,而是執行viewWillAppear方法,因為,loadView和viewDidLoad方法的作用是將視圖加載到內存,而從后一個頁面返回時,前一個頁面已經加載到內存,所以不用再次加載,所以不執行loadView和ViewDidLoad方法;
代理傳值:和代理設計模式一樣,按照設置代理,遵循協議的那四步來就行,
/*
1,定義協議 (BaoMuProtocol)
2,遵循協議的類 (Nurse)
3.定義需要代理的類 (Mother)
4.建立關系 (Mother中定義一個代理類型的成員變量)
*/
新聞熱點
疑難解答