2017-02-08 10 views
0

У меня есть эта часть кода, чтобы добавить новую ячейку в виде коллекции. Делегат и источник данных установлены правильно. Но ячейка просмотра коллекции ничего не показывала. Ну, когда я его отлаживаю, он показывает, что ячейка создана, но ячейка содержит ничего, кроме UIView, где я ожидаю, что она должна содержать UIButton с UIImageView внутри нее.Как получить числовое значение перечисления или задать перечисление с числовым значением в Objective C?

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self setImgGallery:[[NSMutableArray alloc] init]]; 
    [[self cvPictureGallery] registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"new"]; 
    [[self cvPictureGallery] registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"review"]; 

    // add 5 UIImage test to imgGallery. 
    for (int i = 0; i < 5; i++) { 
     [[self imgGallery] addObject:[UIImage named:@"test.png"]]; 
    } 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
    return MIN ([[self imgGallery] count] + 1, 5); 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    if ([indexPath row] == [[self imgGallery] count]) { // show the camera icon 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"new" forIndexPath:indexPath]; 

     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - camera icon 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

      UIImageView * imgCameraIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camera.png"]]; 
      [imgCameraIcon setFrame:CGRectMake(0, 0, 50, 50)]; 
      [imgCameraIcon setContentMode:UIViewContentModeScaleAspectFit]; 

      UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
      [btnCamera addSubview:btnCamera]; 
      [btnCamera addTarget:self action:@selector(openCameraTapped) forControlEvents:UIControlEventTouchUpInside]; 
      [imgCameraIcon setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

      [cell addSubview:btnCamera]; 
      [cell setBackgroundColor:[UIColor whiteColor]]; 
      [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"new"]; 
     } 
     return cell; 
    } 
    else { 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"review" forIndexPath:indexPath]; 
     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - image selected 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

      UIImageView * imgSelected = [[UIImageView alloc] initWithImage:[[self imgGallery] objectAtIndex:[indexPath row]]]; 
      [imgSelected setFrame:CGRectMake(0, 0, 100, 100)]; 
      [imgSelected setContentMode:UIViewContentModeScaleAspectFill]; 
      [imgSelected setTag:1]; 

      UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
      [btnCamera addSubview:btnCamera]; 
      [btnCamera addTarget:self action:@selector(imageTapped) forControlEvents:UIControlEventTouchUpInside]; 
      [imgSelected setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

      [cell addSubview:btnCamera]; 
      [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"review"]; 
     } 
     return cell; 
    } 
} 

Я использовал ссылку на эти QA:

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    if ([indexPath row] == [[self imgGallery] count]) { // show the camera icon 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"new" forIndexPath:indexPath]; 

     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - camera icon 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

      UIImageView * imgCameraIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camera.png"]]; 
      [imgCameraIcon setFrame:CGRectMake(0, 0, 50, 50)]; 
      [imgCameraIcon setContentMode:UIViewContentModeScaleAspectFit]; 
      [imgCameraIcon setTag:1]; 

      UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
      [btnCamera addSubview:imgCameraIcon]; 
      [btnCamera addTarget:self action:@selector(openCameraTapped) forControlEvents:UIControlEventTouchUpInside]; 
      [btnCamera setTag:2]; 
      [imgCameraIcon setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

      [cell addSubview:btnCamera]; 
      [cell setBackgroundColor:[UIColor whiteColor]]; 
      [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"new"]; 
     } 

     UIImageView * imgCameraIcon = (UIImageView *) [cell viewWithTag:1]; 
     [imgCameraIcon setImage:[UIImage imageNamed:@"camera.png"]]; 

     NSLog (@"Subview count:%lu", (unsigned long)[[cell subviews] count]); 

     return cell; 
    } 
    else { 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"review" forIndexPath:indexPath]; 
     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - image selected 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

      UIImageView * imgSelected = [[UIImageView alloc] initWithImage:[[self imgGallery] objectAtIndex:[indexPath row]]]; 
      [imgSelected setFrame:CGRectMake(0, 0, 100, 100)]; 
      [imgSelected setContentMode:UIViewContentModeScaleAspectFill]; 
      [imgSelected setClipsToBounds:YES]; 
      [imgSelected setTag:1]; 

      UIButton * btnImage = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
      [btnImage addSubview:imgSelected]; 
      [btnImage addTarget:self action:@selector(imageTapped) forControlEvents:UIControlEventTouchUpInside]; 
      [btnImage setTag:2]; 
      [imgSelected setCenter:CGPointMake([btnImage width]/2, [btnImage height]/2)]; 

      [cell addSubview:btnImage]; 
     } 

     UIImageView * imgSelected = (UIImageView *) [cell viewWithTag:1]; 
     [imgSelected setImage:[[self imgGallery] objectAtIndex:[indexPath row]]]; 

     NSLog (@"Subview count:%lu", (unsigned long)[[cell subviews] count]); 

     return cell; 
    } 
} 

Результат подсчета подвид всегда 1. Ниже, является рабочий, но подсчет подсчета увеличивается каждый раз.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    if ([indexPath row] == [[self imgGallery] count]) { // show the camera icon 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"new" forIndexPath:indexPath]; 

     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - camera icon 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     } 

     UIImageView * imgCameraIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camera.png"]]; 
     [imgCameraIcon setFrame:CGRectMake(0, 0, 50, 50)]; 
     [imgCameraIcon setContentMode:UIViewContentModeScaleAspectFit]; 

     UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     [btnCamera addSubview:imgCameraIcon]; 
     [btnCamera addTarget:self action:@selector(openCameraTapped) forControlEvents:UIControlEventTouchUpInside]; 
     [imgCameraIcon setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

     [cell addSubview:btnCamera]; 
     [cell setBackgroundColor:[UIColor whiteColor]]; 
     [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"new"]; 

     NSLog (@"Subview count:%lu", (unsigned long)[[cell subviews] count]); 

     return cell; 
    } 
    else { 
     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"review" forIndexPath:indexPath]; 
     if (cell == nil) { 
      /* 
      cell 
      - contentView 
       - button 
       - image selected 
      */ 

      cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     } 

     UIImageView * imgSelected = [[UIImageView alloc] initWithImage:[[self imgGallery] objectAtIndex:[indexPath row]]]; 
     [imgSelected setFrame:CGRectMake(0, 0, 100, 100)]; 
     [imgSelected setContentMode:UIViewContentModeScaleAspectFill]; 
     [imgSelected setClipsToBounds:YES]; 
     [imgSelected setTag:1]; 

     UIButton * btnImage = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     [btnImage addSubview:imgSelected]; 
     [btnImage addTarget:self action:@selector(imageTapped) forControlEvents:UIControlEventTouchUpInside]; 
     [imgSelected setCenter:CGPointMake([btnImage width]/2, [btnImage height]/2)]; 

     [cell addSubview:btnImage]; 
     [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"review"]; 

     NSLog (@"Subview count:%lu", (unsigned long)[[cell subviews] count]); 

     return cell; 
    } 
} 
+0

CollectionView класс регистр должен быть на вершине, прежде чем вы на самом деле назвать dequeReusableCell? – Joshua

+1

@ Joshua после того, как я выбрал правильный ответ, он корректно. Я думаю, вам нужно только зарегистрировать его один раз на всю жизнь этого набораView. –

+0

yup, но, читая выбранный вами ответ, я думаю, что он не повторно использует ячейку должным образом. – Joshua

ответ

1

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
if ([indexPath row] == [[self imgGallery] count]) { // show the camera icon 
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"new" forIndexPath:indexPath]; 

    if (cell == nil) { 
     /* 
     cell 
     - contentView 
      - button 
      - camera icon 
     */ 

     cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
    } 
     UIImageView * imgCameraIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camera.png"]]; 
     [imgCameraIcon setFrame:CGRectMake(0, 0, 50, 50)]; 
     [imgCameraIcon setContentMode:UIViewContentModeScaleAspectFit]; 

     UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     [btnCamera addSubview:btnCamera]; 
     [btnCamera addTarget:self action:@selector(openCameraTapped) forControlEvents:UIControlEventTouchUpInside]; 
     [imgCameraIcon setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

     [cell addSubview:btnCamera]; 
     [cell setBackgroundColor:[UIColor whiteColor]]; 
     [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"new"]; 

    return cell; 
} 
else { 
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"review" forIndexPath:indexPath]; 
    if (cell == nil) { 
     /* 
     cell 
     - contentView 
      - button 
      - image selected 
     */ 

     cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
} 
     UIImageView * imgSelected = [[UIImageView alloc] initWithImage:[[self imgGallery] objectAtIndex:[indexPath row]]]; 
     [imgSelected setFrame:CGRectMake(0, 0, 100, 100)]; 
     [imgSelected setContentMode:UIViewContentModeScaleAspectFill]; 
     [imgSelected setTag:1]; 

     UIButton * btnCamera = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     [btnCamera addSubview:btnCamera]; 
     [btnCamera addTarget:self action:@selector(imageTapped) forControlEvents:UIControlEventTouchUpInside]; 
     [imgSelected setCenter:CGPointMake([btnCamera width]/2, [btnCamera height]/2)]; 

     [cell addSubview:btnCamera]; 
     [collectionView registerClass:[cell class] forCellWithReuseIdentifier:@"review"]; 
    return cell; 
} 

}

+0

О, ты прав. Я забыл, что я положил все в скобки. Большое спасибо! –

+0

просто любопытно, не так ли, если вы снова покажете ячейку, она снова добавит кнопку? это не будет правильно использовать ячейку. он просто добавит btnCamera снова и снова, в конце концов вы заметите это, когда прокрутите слишком много, и он станет медленным. – Joshua

+0

@ Joshua yea вы на самом деле правы. Я добавил 'NSLog (@" Subview count:% lu ", (unsigned long) [[cell subviews] count]);' прямо перед возвратом ячейки, и показывает, что подсчет subview увеличивается каждый раз, когда я вызываю 'reloadData'. Но если я помещаю все внутри скобок, а за пределами скобок я называю их каждый с помощью 'viewWithTag:', а затем загружать изображение там, я все равно ничего не вижу. Подсчет подсчета остается в 1. Я обновил код, чтобы вы могли видеть мой модифицированный код. –

2

Я не уверен, что название вашего вопроса в любом случае связано с вашим запросом, но, пожалуйста, замените строку:

[btnCamera addSubView:btnCamera] 

с

[btnCamera addSubView:imgCameraIcon] 
+0

Это очень полезно. Это промах в моей части. Благодаря! –