2012-12-31 69 views
0

我在故事板中有兩個場景。因爲我不能上傳圖片(新用戶),我們姑且稱之爲場景1和場景2故事板兩個場景。從場景2中的UITableViewCell到場景1中的UILabel的文本

場景1:使用的UITableViewCell一個UILabel,當選擇該單元格,它把你帶到場景2
場景2:爲用戶提供在UITableView中進行選擇的選項。一旦選擇了選項,它會在選中的UITableViewCell旁邊放置一個複選標記。

當我單擊場景2上的保存按鈕時,如何獲取它,它從場景2中選定的UITableViewCell獲取文本,並將用戶帶回場景1,並使用場景2中的文本填充UILabel ?

我用故事板來創建UITableViews。每個單元都有它自己的類。謝謝。

回答

1

使用委託設計模式允許兩個對象相互通信(Apple reference)。

一般:

  1. 創建場景2名爲委託的屬性。
  2. 在場景2中創建一個協議,該協議定義場景2委託人必須定義的方法。
  3. 在從場景1到場景2繼續前,將場景1設置爲場景2的代表。
  4. 當在場景2中選擇一個單元格時,向場景2的代表發送消息以通知代表該選擇。
  5. 允許代表在選擇後處理選擇和解除場景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]; 
} 
+0

謝謝你的迅速回復。所以我遵循你的代碼。誤區三: 場景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

+0

沒問題。這是一個編譯器錯誤b/c編譯器不知道有關STStartTransport類型(即接口聲明在協議聲明之後)。在協議聲明之前添加@class STStartTransport,如上面編輯的版本所示。希望有所幫助。 – Bill

+0

錯誤: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

相關問題