2015-09-28 2 views
1

У меня есть два UITableViews с использованием раскадровки в Xcode 7. Я установил делегат и dataSource с помощью Connections Inspector для обоих представлений таблиц.Вставить UITableView в UITableViewCell в iOS 9, Xcode 7 и раскадровки

Пусть первый вид таблицы будет Основного видом таблицы и пусть вид таблицы в каждой ячейке основного представления таблицы будет мнение таблицы подробно с идентификаторами клеток, названных соответствующим образом и соответственно.

[tableView dequeueReusableCellWithIdentifier:@"MainCell" forIndexPath:indexPath] Когда выполняется, она немедленно вызывает его метод DATASOURCE -cellForRowAtIndexPath: для DetailCell мешает мне настройки пользовательского переменной экземпляра во время добавить соответствующие данные в каждую ячейку.

Ниже приведен упрощенный пример, отмеченный с помощью комментариев.

MainTableViewController:

@implementation MainTableViewController 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    // Keep in mind the following two (2) lines are set using the Connections Inspector 
    //cell.detailTableView.dataSource = cell; 
    //cell.detailTableView.delegate = cell; 

    // Stepping over the following line will jump to the 
    // other `-cellForRowAtIndexPath:` (below) used to set 
    // the detail info. 
    cell = (MainTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MainCell" forIndexPath:indexPath]; 

    CustomObj *obj = self.mainData[indexPath.row]; 
    cell.nameLabel.text = obj.name; 
    cell.additionalInfo = obj.additionalInfo; // This line is not set before instantiation begins for the detail table view... 

    return cell; 
} 

... 

@end 

DetailTableViewCell (содержит UITableView и реализует соответствующие протоколы):

@interface DetailTableViewCell : UITableViewCell <UITableViewDataSource, UITableViewDelegate> 
@property (nonatomic, weak) IBOutlet UILabel *nameLabel; 
@property (nonatomic, weak) IBOutlet UITableView *detailTableView; 
@property (nonatomic, strong) CustomObj *additionalInfo; 
@end 

@implementation DetailTableViewCell 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    cell = (DetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath]; 

    // Instantiate detail ... 
    cell.detailLabel.text = self.additionalInfo.text; 

    // Problem! 
    // self.additionalInfo == nil thus we cannot set a value to the label. 

    return cell; 
} 

... 

@end 

Проблема, когда метод подробно -cellForRowAtIndexPath: называется, я не имел возможность установите значение для своего источника данных, в этом случае additionalInfo.

ответ

1

Есть много возможных способов исправить вашу проблему, но сначала я бы сказал, что ваш дизайн кажется не очень хорошим, у UItableViewCell есть еще один UITableView и еще один UItableViewCell внутри этого UITableView? Почему вы делаете это? Просто используйте один UITableView и поместите все свои представления в один UItableViewCell, поскольку subViews должно быть достаточно.

Теперь получить к вашей проблеме:

Я бы предложил не использовать IBOutlet для настройки вашего делегата и DataSource, используйте код. Это может дать вам возможность отложить настройку dataSource и delgate, когда вы будете готовы. После того, как вы думаете, что это подходящее время, просто позвоните [cell.detailTableView reloadData] вызовет ваш DetailTableViewCell вызывать cellForRowAtIndexPath

@implementation MainTableViewController 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

// Keep in mind the following two (2) lines are set using the Connections Inspector 
//cell.detailTableView.dataSource = cell; 
//cell.detailTableView.delegate = cell; 

// Stepping over the following line will jump to the 
// other `-cellForRowAtIndexPath:` (below) used to set 
// the detail info. 
cell = (MainTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MainCell" forIndexPath:indexPath]; 

CustomObj *obj = self.mainData[indexPath.row]; 

cell.nameLabel.text = obj.name; 
cell.additionalInfo = obj.additionalInfo; // This line is not set before instantiation begins for the detail table view... 

// setup dataSource and delegate now 
cell.detailTableView.dataSource = cell; 
cell.detailTableView.delegate = cell; 
// call reloadData whenever you think is proper 
[cell.detailTableView reloadData]; 

return cell; 
} 
+0

Я забыл, что установка DataSource и делегировать переменные на UITableView с помощью кода может работать в мою пользу. У меня есть только два иерархических уровня UITableViews, и я нахожу это необходимым для этой задачи. Я опустил дополнительный код, поскольку это не имело отношения к проблеме. Спасибо. –

-1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell* cell = nil; 
    //Check this call is for which table view. 
    if(tableView == detailTableView) { 
     cell = (MainTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MainCell" forIndexPath:indexPath]; 
     // Do any additional setup you want with MainCell 

    } else { 
     cell = (DetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath]; 
     // Do any additional setup you want with DetailCell 

    } 

    return cell; 
} 
Смежные вопросы