2014-01-22 3 views
2

У меня вопрос о добавлении UIView в UIcollectionviewcell. У меня есть UIcollectionview и это условие, если условие истинно. Мне нужно добавить UIView в UIcollectionviewcell. Если условие false, не добавляйте. После обновления UIcollectionviewUIView добавлен в Cell, для которого условия истинны и некоторые условия, для которых это условие является ложным. Как добавить UIView в UIcollectionviewcell? один, два или три UIView может быть добавлена ​​ячейка.Добавление UIView к UICollectionviewcell

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{  
NSInteger dayStart = [self dayWeekStart:[self getCurentDate:indexPath.section]]; 

CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

if (indexPath.item+1 < dayStart) { 
    CalendarEmptyCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellemptyIdentifier" forIndexPath:indexPath]; 

    return cell; 

} else { 

    CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    cell.titleLabel.text = [NSString stringWithFormat:@"%i",indexPath.item-dayStart+2]; 

    int todayDayRowInt = todayDayRow; 
    int dayPlusShift = todayDayRowInt + dayStart - 2; 

    cell.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15]; 

    CALayer* layer = [cell layer]; 

    [layer setCornerRadius:15]; 

    dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm:ss Z"; 

    cell.titleLabel.textColor = [UIColor lightGrayColor]; 

    dateFromString1 = [NSDate date]; 

    dateFromString2 = [dateFormatter dateFromString:_dateFinish]; 

    dateFromString3 = [dateFormatter dateFromString:_dateStart]; 


    if ([self checkDateFromCalendar:indexPath.section row:indexPath.item + 3 - dayStart] == 1) { 

     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

     [arrColor removeAllObjects]; 

     for (int i=0; i<appDelegate.selectPill.count; i++) { 

      Pill *arrPill = [appDelegate.selectPill objectAtIndex:i]; 

      NSNumber *mDay = arrPill.manyday; 

      int mDayInt = [mDay integerValue]+1; 

      if ([[self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item + 3 - dayStart] compare:[self sameDateByAddingMonths:arrPill.start addMonths:0 addDay:mDayInt]] == NSOrderedAscending) { 

       NSDate *verifiableDate = [self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item]; 
       NSDate *verifiableDate2 = [self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item+1]; 

       NSTimeInterval diff = [verifiableDate timeIntervalSinceDate:arrPill.start]; 
       NSTimeInterval diff2 = [verifiableDate2 timeIntervalSinceDate:arrPill.start]; 

       yui = (diff2 - diff); 

       NSInteger sss = diff/yui; 

       if (diff >= 0) { 

        float fff = fmod (sss , ([arrPill.frequency doubleValue]+1)); 

        if (fff == 0) { 

         NSArray *components = [arrPill.color componentsSeparatedByString:@","]; 
         CGFloat r = [[components objectAtIndex:0] floatValue]; 
         CGFloat g = [[components objectAtIndex:1] floatValue]; 
         CGFloat b = [[components objectAtIndex:2] floatValue]; 
         CGFloat a = [[components objectAtIndex:3] floatValue]; 
         UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a]; 

         UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0+(i*10), (i*10), 10, 10)]; 
         view.backgroundColor = [UIColor color]; 

         [cell.contentView addSubview:view]; 

        } 
       } 
      } 
     } 

     cell.titleLabel.textColor = [UIColor darkGrayColor]; 

    } else { 

     cell.titleLabel.textColor = [UIColor lightGrayColor]; 

    } 

    if ([dateFromString1 compare:dateFromString2] != NSOrderedDescending && [dateFromString1 compare:dateFromString3] != NSOrderedAscending) { 

     if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){ 

      cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1]; 
      cell.titleLabel.textColor = [UIColor whiteColor]; 
      cell.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15]; 

     } else { 

      cell.backgroundColor = [UIColor whiteColor]; 

     } 

    } 

    return cell; 
} 
return cell; 
} 

ответ

0

Используйте cell.contentView, чтобы получить доступ к UIView ячейки.

Пример:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    static NSString *identifier = @"Cell"; 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; 
    MyRootView *view = [[MyRootView alloc]initWithFrame:CGRectMake(0, 0, 100, 100) someBusinessLogicParam:1]; 
    [cell.contentView addSubview:view]; 
    return cell; 
} 

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

Модифицированный Пример MyRootView:

- (id)initWithFrame:(CGRect)frame someBusinessLogicParam:(NSInteger)bp 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     self.backgroundColor = [UIColor whiteColor]; 
     if (bp == 0) { 
      UIView *yourChild1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
      [self addSubview:yourChild1]; 
     } else if (bp == 1) { 
      UIView *yourChild2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
      [self addSubview:yourChild2]; 
     }else if (bp == 3) { 
      UIView *yourChild3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
      [self addSubview:yourChild3]; 
      UIView *yourChild4 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)]; 
      [self addSubview:yourChild4]; 
     } 
    } 
    return self; 
} 

Вы можете использовать cell.contentView добавить в MyRootView вместе с вашей логикой, что получает отображаться.

+1

Это не работает. – Alexey

+0

Не могли бы вы описать причины, почему они не работают? Вы указали имя «Ячейка» в Идентификаторе в доске объявлений? Ваш метод numberOfItemsInSection возвращает более 0 элементов? Когда вы устанавливаете точку останова. В initWithFrame вашего ViewView он попадает в точку останова? – Xuan

+0

Этот метод добавляет uiview ко всем ячейкам. Если вы используете его с условием, это не сработает. – Alexey

1

Добавьте ваш взгляд визуально на ваш
StoryBoard или XIb файл и сделать классы пользовательских ячейки сделать соединения
Используйте ниже фрагмент кода

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *cellIdentifier = @"Cell"; 

PhotosCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; 
UIView *anotherView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)]; 

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 50.0, 20.0)]; 
label.text = @"Hello"; 

[anotherView addSubview:label]; 

[cell.myView addSubview:anotherView]; 

if("Your condition is true") 
{ 
     cell.myView.hidden = YES; 
} 
else 
{ 
     cell.myView.hidden = YES; 

} 

return cell; 

} 
+0

Это работает, если мне нужно добавить один uiview. Но мне нужно добавить разные количества в другую ячейку uiview. Некоторым мне не нужно добавлять uiview. – Alexey

+0

@Alexey - я отправил свой новый ответ - после того, как у вас есть один UIView, вы также можете добавить subview другого представления - таким образом вы можете добавить пользовательские представления для каждой ячейки. –

+0

Спасибо за вашу помощь. – Alexey

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