2014-03-25 2 views
0

У меня UIImageView, как простая галерея, которая получает данные от JSON.Как создать салфетки для следующего/заднего UIImageView

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil]; 
    NSArray *tmp =[allDataDictionary objectForKey:@"gallery"]; 
    if (tmp.count>0){ 

     for (NSDictionary *diction in tmp) { 
      [self.patternImagesArray addObject:diction]; 
     } 

     NSLog(@"%@", self.patternImagesArray); 
     // [loading stopAnimating]; 

    } 

    [self.collectionView reloadData]; 
} 

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    PatternView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PatternCell" forIndexPath:indexPath]; 

    NSString *myPatternString = [[self.patternImagesArray objectAtIndex:indexPath.row] valueForKey:@"thumb"]; 

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:myPatternString]]; 
    cell.patternImageView.image = [UIImage imageWithData:data]; 

    return cell; 


} 

Для полных изображений я использую это:

-(void)viewDidLoad{ 

    NSString *path=[_newsData valueForKey:@"bigimg"]; 

    NSData* imageData = [NSData dataWithContentsOfURL: [NSURL URLWithString: path]]; 

    UIImage* image = [UIImage imageWithData: imageData]; 

     NSLog(@"%@", image); 

    _imageParse.image = image; 

    [_PanelTools setHidden:YES]; 


} 

Когда я нажать на любом изображении в моем CollectionViewCell я могу увидеть полное изображение, но как создать проведите палец влево/вправо для просмотра следующего изображения и обратно , Я знаю, как сделать салфетки в любую сторону, но как создать прокрутку с изображением рядом/назад.

enter image description here

+0

где вы показать полное изображение? на отдельном viewController или на вид того же viewController, что и UICollectionView? – ZeMoon

+0

На отдельном ViewController – Genevios

+0

ОК, обновит мой ответ в течение нескольких минут – ZeMoon

ответ

5

Во-первых, создать два метода, -nextImage и -prevImage и поместить в код для отображения следующей и предыдущей изображения соответственно.

Затем добавить салфетки жест распознавателей используя следующий код в -viewDidLoad:

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeImage:)]; 
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; 
[_imageParse addGestureRecognizer:swipeLeft]; 

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeImage:)]; 
swipeRight.direction = UISwipeGestureRecognizerDirectionRight; 
[_imageParse addGestureRecognizer:swipeRight]; 

Чтобы иметь возможность показать изображения, ваша потребность в первый отправить весь массив данных вместо словаря с текущим элементом , Для этого преобразуем свойство _newsData в NSArray и где вы устанавливаете словарь текущего элемента в новом viewController, вместо этого задайте все данные. Кроме того, введите новую переменную. Как так:

@property (strong, nonatomic) NSArray *newsData; 
@property NSInteger currentIndex; 

Ввести метод для показа изображения на основе индекса

-(void)showImageAtIndex:(NSInteger)index 
{ 
    NSString *path=[[_newsData objectAtIndex:index] objectForKey:@"bigimg"]; 
    NSData* imageData = [NSData dataWithContentsOfURL: [NSURL URLWithString: path]]; 

    UIImage* image = [UIImage imageWithData: imageData]; 

    NSLog(@"%@", image); 

    _imageParse.image = image; 
} 

Теперь в вашем методе viewDidLoad установить текущее изображение как:

[self showImageAtIndex:_currentIndex]; 

-swipeImage метод должен выглядеть примерно так:

-(void)swipeImage:(UISwipeGestureRecognizer*)recognizer 
{ 
    NSInteger index = _currentIndex; 

    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) 
    { 
     index++; 
    } 
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) 
    { 
     index--; 
    } 

    if (index > 0 || index < ([_newsData count] - 1)) 
    { 
     _currentIndex = index; 
     [self showImageAtIndex:_currentIndex]; 
    } 
    else 
    { 
     NSLog(@"Reached the end, swipe in opposite direction"); 
    } 

} 

Вот что ваш -prepareForSegue метод класса GalleryControllerCollection должен выглядеть следующим образом:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    PatternView *cell = (PatternView *)sender; 
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell]; 

    GalleryControllerFullmage *vc = (GalleryControllerFullmage*)segue.destinationViewController; 
    vc.newsData = [_patternImagesArray copy]; 
    vc.currentIndex = indexPath.row; 
} 

Имя в SEGUE, который переходит из состояния коллекции с точки зрения изображения, как «goToFullImage»

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [self performSegueWithIdentifier:@"goToFullImage" sender:[collectionView cellForItemAtIndexPath:indexPath]]; 
} 
+0

Я знаю, как создать Swipe, я не знаю, как создать следующее/обратное изображение, которое анализирует JSON. – Genevios

+0

Ваш вопрос казался таким, будто вы спрашивали об этом. Пожалуйста, перефразируйте его. – ZeMoon

+0

Так что, пожалуйста, посмотрите на изображение по моему вопросу – Genevios

1

Включить UIImage зрения пользователя которое по умолчанию отключено.

[imageView setUserInteractionEnabled:YES]; 

Добавление Размах Жест События

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 

// Установка направления салфетки.

[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft]; 
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight]; 

Обработка Размах Жест События

- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe { 

    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) { 

     NSLog(@"Left Swipe"); 

    } 

    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) { 

     NSLog(@"Right Swipe"); 

    } 

} 
Смежные вопросы