UICollection View - Segue - выбрал конкретную ячейку, LOG

Я начинаю использовать UICOllectionview для загрузки сделанного на заказ фотоальбома, альбом загружается просто отлично, и данные поступают с моего сервера (SQL-JSON-NSARRAY-NSDictionary) и заполняются в ячейке просто отлично, однако теперь я хотелось бы, чтобы пользователь выбирал эту ячейку для загрузки нового UIVIewController с этим изображением в полном размере (чтобы они могли просматривать/печатать/делиться и т. д.)

Однако я застреваю в методе «подготовки к переходу», так как не могу извлечь какую-либо информацию из этой конкретной ячейки.

в качестве теста прямо сейчас я просто хочу, чтобы NSLOG сказал: «Пользователь выбрал НАЗВАНИЕ АЛЬБОМА% @»

Вот мой код до сих пор, любая помощь будет принята с благодарностью...

#import "AlbumViewController.h"
#import "AlbumCustomCell.h"
#import "PhotosInAlbumsViewController.h"

@interface AlbumViewController ()

@end

@implementation AlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /// Grab Photo Album information (pics,title,date) From Server



    NSString *myURL1 = [ NSString stringWithFormat:         @"http://mywebsiteaddress.com/index.php"];
    NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:myURL1]];
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSArray *items = [json objectForKey:@"users"];
    photoalbumarray = items;
   // NSLog(@"%@", photoalbumarray);
}

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


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

}

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"CelliD";
    AlbumCustomCell *myCell = (AlbumCustomCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    // this above states to setup the cell using the Identifier I specified in Sotry board, so that cell is constantly reused

    if (indexPath.section == 0) { 
         NSDictionary *item = [photoalbumarray objectAtIndex:[indexPath row]];
myCell.titleincell.text = [item objectForKey:@"title"]; // this puts the title in the cell
        teststring = [item objectForKey:@"title"];

        myCell.dateincell.text = [item objectForKey:@"date"]; // this puts the date in the     data label in the cell


      //  myCell.imageincell1.image = [UIImage imageNamed:[item objectForKey:@"img1"]]; // this puts the picture in the cell
         myCell.imageincell2.image = [UIImage imageNamed:[item objectForKey:@"img2"]]; // this puts the picture in the cell
         myCell.imageincell3.image = [UIImage imageNamed:[item objectForKey:@"img3"]]; // this puts the picture in the cell

        // IMAGE 1
        NSString *picture1 = [item objectForKey:@"img1"];
        NSURL *imageURL1 = [NSURL URLWithString:picture1];
        NSData * imageData1 = [NSData dataWithContentsOfURL:imageURL1];
        UIImage * image1 = [UIImage imageWithData:imageData1];
        myCell.imageincell1.image = image1;

    myCell.imageincell1.alpha = 0.0;
    [UIView animateWithDuration:1.5 animations:^{
        myCell.imageincell1.alpha = 1.0;
    }];


    // IMAGE 2
    NSString *picture2 = [item objectForKey:@"img2"];
    NSURL *imageURL2 = [NSURL URLWithString:picture2];
    NSData * imageData2 = [NSData dataWithContentsOfURL:imageURL2];
    UIImage * image2 = [UIImage imageWithData:imageData2];
    myCell.imageincell2.image = image2;

    myCell.imageincell2.alpha = 0.0;
    [UIView animateWithDuration:1.5 animations:^{
        myCell.imageincell2.alpha = 1.0;
    }];



    // I MAGE 3
    NSString *picture3 = [item objectForKey:@"img3"];
    NSURL *imageURL3 = [NSURL URLWithString:picture3];
    NSData * imageData3 = [NSData dataWithContentsOfURL:imageURL3];
    UIImage * image3 = [UIImage imageWithData:imageData3];
    myCell.imageincell3.image = image3;
    myCell.imageincell3.alpha = 0.0;
    [UIView animateWithDuration:1.5 animations:^{
        myCell.imageincell3.alpha = 1.0;
    }];

}
return myCell;
}



// SEGUE TRANSITION FROM ALBUMS TO PHOTO
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showPhotoAlbum"]) {
        NSLog(@"Prepare for Segue to load Specific Photo Album");
        NSLog(@"User Selected this cell or the name of the title in the cell which comes from a NSDictionary =>");
// EXAMPLE NSLOG TO SHOW =>  User Selected - Album Name
// Where album name is actually the album name grabbed form the server based on the selected row
    }
}

@end

и просто чтобы вы могли видеть мои данные JSON с сервера, вот это

2012-10-01 13:02:53.856 CB Photo[3957:907] (
        {
        date = "2012-10-01 07:23:01";
        id = 1;
        img1 = "http://b2fdev.ca/demo/CBPhoto/pic1.jpg";
        img2 = "http://b2fdev.ca/demo/CBPhoto/pic2.jpg";
        img3 = "http://b2fdev.ca/demo/CBPhoto/pic3.jpg";
        title = "Paul and Jenna's Wedding 2012";
    },
        {
        date = "2012-10-01 05:23:23";
        id = 2;
        img1 = "http://core1.ca/wp-content/themes/custom-community/images/block4.png";
        img2 = "http://core1.ca/wp-content/themes/custom-community/images/block3.png";
        img3 = "http://core1.ca/wp-content/themes/custom-community/images/block2.png";
        title = "Core 1";
    }
)

person Knitsu    schedule 01.10.2012    source источник


Ответы (4)


Вы имеете в виду это?

NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
DetailViewController *destViewController = segue.destinationViewController;

NSIndexPath *index = [indexPaths objectAtIndex:0];

NSLog(@"%d", index.section * 2 + index.row);

этот индекс печати в массиве в 2 раза больше любого массива;

person kafejo    schedule 09.10.2012
comment
У меня был только 1 раздел, поэтому я хотел, чтобы индекс был массивом. Поэтому я использовал index.Item после использования вашего кода. - person Chucky; 07.07.2016

Как я это делаю, я сохраняю частную переменную-член в моем контроллере представления коллекции:

NSInteger selectedPhotoIndex;

Он обновляется каждый раз, когда пользователь выбирает что-то в представлении коллекции:

- (void)collectionView:(UICollectionView *)collectionView 
            didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    selectedPhotoIndex = indexPath.row;
}

Затем я просто использую его в своем методе prepareForSegue. Применительно к вашему случаю это будет выглядеть примерно так:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"ShowPhotoAlbum"]) {
        NSLog(@"User selected %@", [[photoalbumarray objectAtIndex:selectedPhotoIndex] objectForKey:@"title");
        // ... find the right detail VC, set its data, set up delegate etc.
    }
}

Это довольно просто, потому что в этом случае у меня есть только один раздел в представлении коллекции. Если у вас несколько разделов, просто поддерживайте экземпляр NSIndexPath вместо простого целого числа.

person Jere Käpyaho    schedule 11.10.2012
comment
Да, это лучший подход, так как didSelection.... вызывается перед методом prepareForSegue. - person Thomas Decaux; 17.04.2013
comment
Я использую именно этот метод, и переход срабатывает до didSelectRow - person thefoyer; 13.03.2014

Чтобы получить выбранный элемент в вашем источнике данных, вы можете использовать:

[self.collectionView indexPathsForSelectedItems];

Он возвращает массив indexPath. Затем вы можете настроить целевой контроллер представления следующим образом:

NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
ViewController *destinationViewController = (ViewController *)segue.destinationViewController;
destinationViewController.myPropertyToSet = [self.photoalbumarray objectAtIndex:[[test objectAtIndex:0] row]]; // You may have to store it in a proper NSindexPath object before or cast it

Я получаю только индекс 0, но вы можете запросить любой индекс, возвращаемый в массиве indexPaths. Также не забудьте убедиться, что массив не пустой (обычно так и должно быть, но на всякий случай)

person foOg    schedule 03.10.2012

Вы также можете использовать параметр отправителя

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

Отправителем будет UICollectionViewCell или подкласс, который запустил переход.

Это может помочь очистить ваш код.

Итак, в качестве примера кода, предусмотренного в исходном вопросе

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [super prepareForSegue:segue sender:sender];

    id destination = segue.destinationViewController;

    if ([sender isKindOfClass:[AlbumCustomCell class]])
    {
        AlbumCustomCell *cell = sender;
        // set something on destination with a value from the cell
    }
}
person Community    schedule 16.07.2013