2017-02-05 2 views
0

Структура моего приложения в настоящее время выглядит так: Collection View Controller -> Generic Cell со встроенным табличным представлением -> отдельные ячейки.Как вызвать метод в контроллере родительского представления из ячейки ячейки?

Я хотел бы назвать метод в контроллере представления коллекции из одной из отдельных ячеек. До сих пор я реализовал делегат в отдельной ячейке, но если я не могу показать свой делегат в контроллере представления коллекции, потому что у меня нет его экземпляра.

Кроме того, у меня есть несколько ячеек внутри представления таблицы, которые необходимы для доступа к методам в контроллере представления коллекции.

+0

Простой способ заключается в использовании NSNotificationCenter – GeneCode

ответ

1

responder chain может помочь.

Вид может запрашивать цепочку ответчиков для первой цели, которая может принимать сообщение. Предположим, что сообщение -fooBar, то вид может запросить цель с помощью метода -[UIResponder targetForAction:sender:]

// find the first responder in the hierarchy that will respond to -fooBar 
id target = [self targetForAction:@selector(fooBar) sender:self]; 

// message that target 
[target fooBar]; 

Обратите внимание, что эта связь управляется с помощью этого метода:

(BOOL)canPerformAction:(SEL)action 
      withSender:(id)sender; 

реализация Это по умолчанию этот метод возвращает ДА, если класс ответчика реализует запрошенное действие и вызывает следующего ответчика, если он этого не делает.

По умолчанию, первый объект, который отвечает на это сообщение будет цель, так что вы можете переопределить canPerformAction:withSender:, если это необходимо для некоторых видов или просмотреть контроллеры.

0

Для этого вы можете сделать так:

В коллекции View Controller ->.h файл

@interface CollectionViewController : UICollectionViewController<ColectionCellDelegate> 

@end 

В коллекции View Controller ->.m файл

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 
    return [self.collectionData count]; 
} 

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath]; 
    cell.cellData = [self.collectionData objectAtIndex:indexPath.row]; 
    cell.delegate = self; 
    return cell; 
} 

-(void)tableCellDidSelect:(UITableViewCell *)cell{ 
    NSLog(@"Tap %@",cell.textLabel.text); 
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil]; 
    detailVC.label.text = cell.textLabel.text; 
    [self.navigationController pushViewController:detailVC animated:YES]; 
} 

В CollectionCell.h

@class CollectionCell; 
@protocol ColectionCellDelegate 
-(void)tableCellDidSelect:(UITableViewCell *)cell; 
@end 

@interface CollectionCell : UICollectionViewCell<UITableViewDataSource,UITableViewDelegate> 
@property(strong,nonatomic) NSMutableArray *cellData; 
@property(weak,nonatomic) id<ColectionCellDelegate> delegate; 
@end 

В CollectionCell.m

@implementation CollectionCell 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     self.cellData = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 
-(void) awakeFromNib{ 
    [super awakeFromNib]; 
    self.cellData = [[NSMutableArray alloc] init]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return [self.cellData count]; 
} 

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: 
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    static NSString *CellIdentifier = @"TableCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 
    cell.textLabel.text = [self.cellData objectAtIndex:indexPath.row]; 

    return cell; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    [[self delegate] tableCellDidSelect:cell]; 
}