頁面傳值
如果有兩個頁面A和B之前需要傳值,如下圖所示,從A頁面打開一個B頁面,填入一些信息後,展現在B頁面。這個過程需要從B頁面傳數據給A頁面。
A->B的數據傳遞可以在segue中實現,B->A的數據傳遞則用delegate。下面分別講述這兩種傳值方式。
一.segue傳值
新建一個Single View應用,並在stroyboard中拖入一個viewController.並添加相應的控件,如下圖所示,然後建立“編輯”按鈕到頁面2的model segue.
新建一個SecondViewController類,與第一個頁面綁定,並關聯標題和價格的textField屬性。它將接收第一個頁面傳過來的默認值。
在第一個頁面中,關聯標題和價格的內容label屬性。並給它們設置一個默認值。如下圖所示。
在TestViewController.m中重寫prepareForSegue方法,將默認值傳給第二個頁面。
UIViewController *viewController=segue.destinationViewController;
SecondViewController *secondViewController=(SecondViewController *)viewController;
secondViewController.defaultTitleValue=self.titleLabel.text;
secondViewController.defaultPriceValue=self.priceLabel.text;
}
在SecondViewController.m的viewDidload方法中加入兩條賦值語句,如下所示。
{
[super viewDidLoad];
self.titleTextField.text=self.defaultTitleValue;
self.priceTextField.text=self.defaultPriceValue;
}
運行,當跳轉到第二個頁面時,textfield中被填充了默認值 。
二、delegate傳值
由於segue是單向的由A到B,那麼在segue中怎麼把B中產生的data傳遞給A。從頁面B傳值給A,單純用segue難以實現。我們使用ios中一個很重要的模式,delegate。
delegate的出現與mvc(model-view-controller),protocol密切相關。 下面講述使用delegate進行傳值的思路。
一般情況下,我們會想到傳一個A指針給B,當B產生了數據後,再調用A的設置方法就可以了。因此,在B中設置一個delegate屬性,把它賦值爲A,就可以實現上述思路。但是這並不是delegate的真相。
delegate與protocol密切相關,可以類似的理解爲java中的interface。有了這一含義之後,delegate可以做的事情更多。例如有兩個頁面。可以共用一個B頁面進行寶貝詳情的編輯,編輯好後,返回A1或A2都可以,只要它們都實現了PassValueDelegate協議,然後B的delegate屬性設置爲實現了PassValueDelegate協議的類。
更多信息參考:delegate和protocol
下面介紹實現過程:
1.新建一個PassValueDelegate類,並在PassValueDelegate.h中聲明一個protocol,代碼如下。
PassValueDelegate Protocol中聲明瞭一個setValue方法,繼承此協議的類需要實現此方法。
#import <Foundation/Foundation.h>@protocol PassValueDelegate <NSObject>
-(void)setValue:(NSDictionary *)dictionary;
@end
@interface PassValueDelegate : NSObject
@end
2.在TestViewController繼承PassValueDelegate,代碼如下
#import "PassValueDelegate.h"
@interface TestViewController : UIViewController<PassValueDelegate>
.......
3.在SecondViewController中聲明一個Delegate屬性,它是繼承了PassValueDelegate的對象
4.在TestViewController.m中實現PassValueDelegate聲明的方法。
-(void)setValue:(NSDictionary *)dictionary{
self.titleLabel.text=[dictionary objectForKey:@"titleValue"];
self.priceLabel.text=[dictionary objectForKey:@"priceValue"];
}
#pragma mark end
5.將第二個頁面的確定按鈕關聯一個IBAction
並在自動生成的passValue代碼中實現setValue方法的調用。
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:self.titleTextField.text,@"titleValue",self.priceTextField.text,@"priceValue", nil];
[self.delegate setValue:dictionary];
[self dismissViewControllerAnimated:YES completion:nil];
}
6.delegate賦值,在prepareForSegue方法中加入delegate賦值語句,代碼如下
UIViewController *viewController=segue.destinationViewController;
SecondViewController *secondViewController=(SecondViewController *)viewController;
secondViewController.defaultTitleValue=self.titleLabel.text;
secondViewController.defaultPriceValue=self.priceLabel.text;
//delegate賦值
secondViewController.delegate=self;}
7.運行,在編輯頁面中輸入信息,點擊確定後,在第一個頁面中展示。
from:http://www.taobaotest.com/blogs/2381