使用委託設計模式允許兩個對象相互通信(Apple reference)。
一般:
- 創建場景2名爲委託的屬性。
- 在場景2中創建一個協議,該協議定義場景2委託人必須定義的方法。
- 在從場景1到場景2繼續前,將場景1設置爲場景2的代表。
- 當在場景2中選擇一個單元格時,向場景2的代表發送消息以通知代表該選擇。
- 允許代表在選擇後處理選擇和解除場景2。
並且作爲示例:
場景2接口
@class LabelSelectionTableViewController
@protocol LabelSelectionTableViewControllerDelegate
- (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option;
@end
@interface LabelSelectionTableViewController : UITableViewController
@property (nonatomic, strong) id <LabelSelectionTableViewControllerDelegate> delegate;
@end
場景2實施
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.delegate labelSelectionTableViewController:self didSelectOption:cell.textLabel.text];
}
場景1個實施
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.destinationViewController isKindOfClass:[LabelSelectionTableViewController class]] == YES)
{
((LabelSelectionTableViewController *)segue.destinationViewController).delegate = self;
}
}
// a selection was made in scene 2
- (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option
{
// update the model based on the option selected, if any
[self dismissViewControllerAnimated:YES completion:nil];
}
謝謝你的迅速回復。所以我遵循你的代碼。誤區三: 場景1 = STLetsMeet 場景2 = STStartTransport 錯誤1是STStartTransport.h:
@ protocol STStartTransportDelegate - (void)stStartTransport:(STStartTransport *)stStartTransport didSelectOption:(NSString *)option; // I get an error on this line: !Expected a type @end //Rest of the code in that file is fine as below: @ interface STStartTransport : UITableViewController @ property (nonatomic, strong) id delegate; @ end
– user1107173沒問題。這是一個編譯器錯誤b/c編譯器不知道有關STStartTransport類型(即接口聲明在協議聲明之後)。在協議聲明之前添加@class STStartTransport,如上面編輯的版本所示。希望有所幫助。 – Bill
錯誤:2和3處於相同的prepareForSeque代碼中。 STLetsMeet.m - (無效)prepareForSegue:(UIStoryboardSegue *)賽格瑞發件人:(ID)發送方 { 如果([segue.destinationViewController isKindOfClass:[STStartTransport]] == YES)//錯誤2:預期標識符 { ((STStartTransport *)segue.destinationViewController)。委託=自我; //錯誤3:從不兼容類型'STLetsMeet * const_strong' } } }分配給'id'最後,您提到了以下步驟: 5.在場景1到場景2之前,將場景1設置爲場景2的代表。 –
user1107173