0

Привет Я пытаюсь получить доступ к информации ячейки ячейки UICollection через UIsegmentedcontrol.Невозможно получить доступ к информации о ячейке отображения UICollection

В представлении коллекции у меня есть четыре метки и UIsegmented control. При нажатии на сегментированный элемент управления я хочу отображать значения меток.

вот мой код.

- (UIView *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath]; 
cell.mySegmentedControl.tag = indexPath.row; 
selectedSegment = cell.mySegmentedControl.selectedSegmentIndex; 
[cell.mySegmentedControl addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged]; 
cell.caseid.text=[tmpDict objectForKey:@"CaseId"]; 
caseid = [tmpDict objectForKey:@"CaseId"]; 
} 

- (void) segmentValueChanged: (UISegmentedControl *) sender { 
//NSInteger index = sender.tag; 
if(sender.selectedSegmentIndex == 0) 
{ 
NSString *localcaseid = caseid; // it shows default value may be first cell value. 
CollectionViewCell * cell = [[CollectionViewCell alloc]init]; 
NSString *localcaseid = cell.caseid.text; //it prints null value 
} 
else 
{ 
} 

Приведенные выше код не работает для me.any помощи будет appreciated.I хочет отобразить информацию для этой конкретной ячейки.

+0

Вы получаете контроллер внутри segmentValueChanged (метод //) ? – Aneesh

+0

no ............. –

+0

Основная проблема заключается в том, что вы не отслеживаете экземпляр UICollectionViewCell. Когда вы создаете новый экземпляр 'UICollectionViewCell', caseid не будет тем, который вы ожидаете. Проблема может быть решена, если вы создадите пользовательский делегат и передаете ячейку в качестве параметра в нее. Если вам нужна дополнительная помощь, дайте мне знать. – dirtydanee

ответ

1
if(sender.selectedSegmentIndex == 0) { 
     NSString *localcaseid = caseid; 
     NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0]; 
     CollectionViewCell *cell = (CollectionViewCell *)[CollectionView cellForItemAtIndexPath:tempIndexPath]; 
     NSString *localcaseid = cell.caseid.text; 
     NSLog(@"%@",localcaseid); 
    } 
    else { 
    } 
+0

CollectionViewCell * cell = [self.myCollectionView cellForItemAtIndexPath: tempIndexPath]; Я пробовал, как this.It показывает несовместимый указатель –

+0

Он печатает только для первой ячейки. –

+0

теперь проверьте это i обновленный ответ –

1
// CustomCell.h 

#import <UIKit/UIKit.h> 
@protocol CollectionViewCellDelegate; 

@interface CustomCollectionViewCell : UICollectionViewCell 

@property(weak, nonatomic) id<CollectionViewCellDelegate> delegate; 

@end 

// CustomCell.m 

#import "CollectionViewCell.h" 

// Create your delegate 
@protocol CollectionViewCellDelegate <NSObject> 
- (void)collectionViewCell:(CustomCollectionViewCell *)cell segmentedControlChangedValue:(UISegmentedControl *)control; 
@end 

@implementation CustomCollectionViewCell 

// Implement this delegate call on the cell, not on the viewController 
- (void) segmentValueChanged: (UISegmentedControl *) sender { 
    // Call your delegate with the cell added as parameter 
    [self.delegate collectionViewCell:self segmentedControlChangedValue:sender]; 
} 

@end 

В вашем ViewController, убедитесь, что он подтверждает делегату, добавить <CollectionViewCellDelegate> рядом с декларацией ViewController и импортировать ячейки заголовка файла.

ViewController.h

#import "CustomCollectionViewCell.h" 

@interface ViewController : UIViewController <CollectionViewCellDelegate> 

// ViewController.m

// Присвоить делегата в cellForItem вам VC

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    // create your cell 
    // assign your cell's delegate to self 
    cell.delegate = self 
} 

    // Declare the delegate method on the viewController 
    - (void)collectionViewCell:(CustomCollectionViewCell *)cell segmentedControlChangedValue:(UISegmentedControl *)control { 
     // here you now have access to the cell, where the segmented was pressed in 
     // Do what you need to and make sure you reload the data at the end of this function, when you have set up your cell 

     [self.collectionView reloadData]; 
    }