изменить изображение ячейки в методе uicollectionview didSelectItemAtIndexPath

Я построил контроллер CollectionView с фиксированным изображением в 4 ячейках. Я бы хотел, чтобы imageView менялся при выборе ячейки. Не могли бы вы помочь мне с этим?

Спасибо

вот мой код

Контроллер CollectionView .m

....

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

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"     forIndexPath:indexPath];

    UIImage *image;

    int row = [indexPath row];

    image = [UIImage imageNamed:@"ICUbedGREEN.png"];

    myCell.imageView.image = image;

    return myCell;
}

Я бы хотел, чтобы изображение менялось при печати, но я не могу этого понять...

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:    (NSIndexPath *)indexPath
{
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"ICUbedRED.png"]];

    cell.imageView.image = .....

     NSLog(@"elementselected");

}


person dottorfeelgood    schedule 02.01.2013    source источник


Ответы (2)


в вашем подклассе для UICollectionViewCell реализуйте метод прослушивания KVO. Убедитесь, что вы установили для множественного выбора значение true, если хотите, чтобы он был отменен.

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
 if ([keyPath isEqualToString@"selected"])
 {
      // check value of self.selected to know what you are currently.
      // change picture of image here
 }

}

в вашем методе инициализации ячеек вам нужно будет добавить себя в качестве слушателя, чтобы

 [self addObserver:self forKeyPath:@"selected" options:nil context:nil];
person Samuel    schedule 02.01.2013

Это может быть самый глупый ответ на ваши вопросы, но это сработало для меня. Я не знаю, как работать с путями значений KEY, как заявил Самуэль.

В основном я сделал NSMutableArray для хранения состояния значков, красных или зеленых... ДА или НЕТ...

selState = [[NSMutableArray alloc] initWithObjects:@"NO",@"NO",@"NO",@"NO",nil ];

а затем в методе «ItemForIndexPath» проверил значение для установки изображения для этого элемента

if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
    image = [UIImage imageNamed:@"ICUbedGREEN.png"];
}
else
{
    image = [UIImage imageNamed:@"ICUbedRED.jpg"];
}

Когда элемент выбран, с помощью IndexPath изменяется значение NO на YES или наоборот.

if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
    [selState replaceObjectAtIndex:indexPath.row withObject:@"YES"];
}
else if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"YES"]) {
    [selState replaceObjectAtIndex:indexPath.row withObject:@"NO"];
}

А потом обновил коллекцию View

[self.collectionView reloadData];

ВЕСЬ КОД ЗДЕСЬ

@interface ViewController (){
NSMutableArray *selState;
}
@end
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

    selState = [[NSMutableArray alloc] initWithObjects:@"NO",@"NO",@"NO",@"NO",nil ];
}

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

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
             cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    UIImage *image;


    if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
        image = [UIImage imageNamed:@"ICUbedGREEN.png"];
    }
    else
    {
        image = [UIImage imageNamed:@"ICUbedRED.jpg"];
    }


    myCell.imageView.image = image;

    return myCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:        (NSIndexPath *)indexPath
{
    if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
        [selState replaceObjectAtIndex:indexPath.row withObject:@"YES"];
    }
    else if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"YES"]) {
        [selState replaceObjectAtIndex:indexPath.row withObject:@"NO"];
    }

    [self.collectionView reloadData];
}

@end

Спасибо

РЕДАКТИРОВАНИЕ---->>

приведенный выше код в ItemForIndexPath также можно записать в

image = [[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"] ?
             [UIImage imageNamed:@"ICUbedGREEN.png"] : [UIImage imageNamed:@"ICUbedRED.jpg"];

ЗАВЕРШИТЬ РЕДАКТИРОВАНИЕ

person Taseen    schedule 03.01.2013