2016-09-13 2 views
2

Примечание: Я не хочу использовать какие-либо сторонние библиотекиКак реализовать делегат и DataSource методы UICollectionView, когда он находится внутри пользовательских TableViewCell в прошивке, цель C

  • Я имею tableview с с обычай table view cell (рабочий стол хорошо работает).
  • Теперь внутри table view cell Я хочу реализовать collection view.
  • Теперь моя проблема в том, где я должен реализовать методы delegate и методы data source для вида коллекции, который находится внутри custom table view cell. ниже - это то, что я пробовал.

реализация Tabel View Controller

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tvcell"]; 

    return cell; 
} 

работает правильно

Теперь внутри этого FirstTableViewCell есть collection view.

Это мой FirstTableViweCell.h Файл

#import <UIKit/UIKit.h> 

@interface FirstTableViewCell : UITableViewCell<UICollectionViewDelegate,UICollectionViewDataSource> 
@property (weak, nonatomic, nullable) IBOutlet UICollectionView *insideCollectionView; 

@property (strong, nonnull,nonatomic) NSArray *mycollectionData; 
- (void)setColletionData :(nonnull NSArray *)collectionData; 

@end 

и это мой FirstTableViewCell.m Файл

#import "FirstTableViewCell.h" 

@implementation FirstTableViewCell 

- (void)awakeFromNib { 
    [super awakeFromNib]; 
    self.insideCollectionView.delegate = self; 

    // Initialization code 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 

- (void)setColletionData:(NSArray *)collectionData 
{ 
    self.mycollectionData = collectionData; 
    [self.insideCollectionView reloadData]; 
} 


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 
{ 
    return 1; 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return 10; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvcell" forIndexPath:indexPath]; 
    return ccell; 
} 

@end 

следующий метод

- (void)setColletionData:(NSArray *)collectionData 
    { 
     self.mycollectionData = collectionData; 
     [self.insideCollectionView reloadData]; 
    } 

Я использовал для установки array для collectionView, в cellforrowatindexpath в tableview

Так что правильный способ реализации DataSource и Delegate методов для CollectionView, который находится внутри Custom Table View Cell.

+0

Вы делаете отлично. :) –

ответ

1

Horraaaaaaaay ..... = D Это завершенный ответ на это.

Реализация таблицы представления.м-файл

#import "ViewController.h" 
#import "FirstTableViewCell.h" 

@interface ViewController() 

@end 

@implementation ViewController 
{ 
    NSArray *bbarray; 

} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    bbarray = [NSArray arrayWithObjects:@"33",@"44", nil]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tvcell"]; 

    [cell setColletionData:bbarray]; 

    return cell; 
} 

@end 

Реализация внутри пользовательского Table View клетки

настраиваемая таблица файл .h вид

#import <UIKit/UIKit.h> 
@interface FirstTableViewCell : UITableViewCell<UICollectionViewDelegate,UICollectionViewDataSource> 
@property (weak, nonatomic, nullable) IBOutlet UICollectionView *insideCollectionView; 

@property (strong, nonnull,nonatomic) NSArray *mycollectionData; 
- (void)setColletionData :(nonnull NSArray *)collectionData; 

@end 

настраиваемая таблица файл представления .m

#import "FirstTableViewCell.h" 

@implementation FirstTableViewCell 


- (void)awakeFromNib { 
    [super awakeFromNib]; 

    // These two are very important. 
    self.insideCollectionView.delegate = self; 
    self.insideCollectionView.dataSource = self; 

    // Initialization code 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 


//this method is used to set the data , call it in cell for row at index path in table view implementation. 
    - (void)setColletionData:(NSArray *)collectionData 
    { 
     self.mycollectionData = collectionData; 
     [self.insideCollectionView reloadData]; 
    } 


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 
{ 
    return 1; 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    NSLog(@"%lu", (unsigned long)self.mycollectionData.count); 
    return [self.mycollectionData count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvcell" forIndexPath:indexPath]; 
    return ccell; 
} 

@end 
1

У вас есть по существу правильные. Единственное реальное изменение, которое вам нужно, - это обновить источник данных коллекционного представления и делегировать методы в пользовательском классе ячеек, чтобы они правильно ссылались на self.mycollectionData.

Например. Изменение numberOfItemsInSection на:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return self.mycollectionData.count; 
} 
+0

Я сделал это и проверил с точкой останова. для 'self.mycollectionData = collectionData;' он показывает счет как '2', но он не вызывал никаких' делегатов' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'внутри моей ячейки' custom table '. следует вызвать 'self.insideCollectionView.datasource = self;' внутри метода 'awakeFromNib'. –

+0

yep, я должен назвать self.insideCollectionView.datasource = self; в бодрствовании от метода nib. теперь он отлично работает. спасибо в продвинутом, и я поддержал вас. –