2017-01-19 3 views
2

В моем приложении iOS у меня есть панель вкладок с двумя вкладками, как показано ниже. Для каждой вкладки я создал объект UITableView программно. enter image description hereКак добавить UITableViewCell из раскадровки в программно созданный объект UITableView?

Я создал панель вкладок, используя коллекцию. Затем я добавил UITableViewCell к контроллеру просмотра из раскадровки.

enter image description here

Так что я получил следующий вид.

enter image description here

Но теперь, когда я запускаю мое приложение, я не могу видеть UITableViewCell. Где я делаю ошибку, я не понимаю. Пожалуйста помоги.

Ниже приведен мой код.

#import "TicketsViewController.h" 
#import "TabBarCollectionViewCell.h" 
#import "TicketTableViewCell.h" 
#import "Constants.h" 

@interface TicketsViewController() <UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource> 

@property (weak, nonatomic) IBOutlet UICollectionView *tabBarCollectionView; 
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *tabBarCollViewFlowLayout; 
@property (weak, nonatomic) NSIndexPath *prevSelecedIndexPath; 
@property (strong, nonatomic) NSArray *tabBarItemNamesArray; 
@property (weak, nonatomic) IBOutlet UIView *parentViewForTableViews; 
@property (weak, nonatomic) UIView *previousView; 
@property (strong, nonatomic) NSMutableArray *tabRespectiveTableViewsArray; 

@end 

@implementation TicketsViewController 

#pragma mark - lazy instantiation 

- (NSArray *)tabBarItemNamesArray { 
    if (!_tabBarItemNamesArray) 
     _tabBarItemNamesArray = @[@"All Tickets", @"Resolved Tickets"]; 

    return _tabBarItemNamesArray; 
} 

- (NSMutableArray *)tabRespectiveTableViewsArray { 
    if (!_tabRespectiveTableViewsArray) 
     _tabRespectiveTableViewsArray = [[NSMutableArray alloc] initWithArray:@[(id)[NSNull null], (id)[NSNull null]]]; 

    return _tabRespectiveTableViewsArray; 
} 

#pragma mark - life cycle 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self.view layoutIfNeeded]; 

    [self tabBarItemNamesArray]; 
    [self tabRespectiveTableViewsArray]; 

    _tabBarCollectionView.delegate = self; 
    _tabBarCollectionView.dataSource = self; 
    _previousView = nil; 

    _tabBarCollViewFlowLayout.itemSize = CGSizeMake(ceilf(_tabBarCollectionView.frame.size.width/2), _tabBarCollViewFlowLayout.itemSize.height); 

    _prevSelecedIndexPath = [NSIndexPath indexPathForItem:0 inSection:0]; 
    [_tabBarCollectionView selectItemAtIndexPath:_prevSelecedIndexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone]; 
} 

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 
} 

- (void)viewDidDisappear:(BOOL)animated { 
    [super viewDidDisappear:animated]; 
} 

#pragma mark - collection view 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
    return _tabBarItemNamesArray.count; 
} 

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

    tabBarCollectionViewCell.tabView.tabTitle = [_tabBarItemNamesArray objectAtIndex:indexPath.row]; 
    if ([_tabRespectiveTableViewsArray objectAtIndex:indexPath.row] == (id)[NSNull null]) { 
     UITableView *tableView = [[UITableView alloc] initWithFrame:_parentViewForTableViews.bounds style:UITableViewStylePlain]; 
     [tableView registerClass:[TicketTableViewCell class] forCellReuseIdentifier:@"TicketTableViewCell"]; 

     tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 
     tableView.showsVerticalScrollIndicator = YES; 
     tableView.showsHorizontalScrollIndicator = NO; 
     tableView.scrollEnabled = YES; 
     tableView.pagingEnabled = NO; 
     tableView.bounces = YES; 
     tableView.userInteractionEnabled = YES; 
     tableView.backgroundColor = [UIColor clearColor]; 

     tableView.translatesAutoresizingMaskIntoConstraints = NO; 
     [_parentViewForTableViews addSubview:tableView]; 
     [_tabRespectiveTableViewsArray replaceObjectAtIndex:indexPath.row withObject:tableView]; 

     [_parentViewForTableViews addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[v0]|" options:0 metrics:nil views:@{@"v0" : tableView}]]; 

     if (_previousView == nil) { 
      [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_parentViewForTableViews attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]]; 
      _previousView = tableView; 
     } 
     else { 
      [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_previousView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.0f]]; 
     } 

     [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_parentViewForTableViews attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]]; 

     tableView.dataSource = self; 
     tableView.delegate = self; 
    } 

    return tabBarCollectionViewCell; 
} 

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { 
    ((TabBarCollectionViewCell *)cell).tabView.tabSelected = cell.isSelected; 

} 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 
    if (_prevSelecedIndexPath) 
     ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:_prevSelecedIndexPath]).tabView.tabSelected = NO; 
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabSelected = YES; 
    _prevSelecedIndexPath = indexPath; 

    [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES]; 
    [((UITableView *)[_tabRespectiveTableViewsArray objectAtIndex:indexPath.row]) reloadData]; 
} 

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath { 
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabHighlighted = YES; 
} 

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath { 
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabHighlighted = NO; 
} 

#pragma mark - table view 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    TicketTableViewCell *ticketTableViewCell = [tableView dequeueReusableCellWithIdentifier:@"TicketTableViewCell" forIndexPath:indexPath]; 

    ticketTableViewCell.labelTime.text = @"02:45 PM"; 

    return ticketTableViewCell; 
} 

#pragma mark - button actions 

- (IBAction)buttonOpenDrawerAction:(id)sender { 
    [[NSNotificationCenter defaultCenter] postNotificationName:SHOW_LEFT_DRAWER object:self]; 
} 

@end 
+0

Вы должны написать TableView delgate и DataSource методы collectionViewcell. – Poles

+0

@ Поля - пожалуйста, проверьте код. Я уже сделал это – appleBoy21

+0

Не получив на самом деле, вопрос не совсем ясен, PLS укажет, где у вас есть табличное представление и на какой части у вас есть viewview. И попытайтесь опубликовать полный образ пользовательского интерфейса. –

ответ

0

Ваш код работы почти сразу, но для лучшего стиля кодирования следующим образом:

  1. Согласно я получаю ваш UITableView находится в UICollectionViewCell, так что кодирование иерархии для вашей точки зрения, т.е. сделать UITableView кода в файле UICollectionViewCell. Привязать UITableViewdelegate \ datasouce с файлом UICollectionViewCell и привязать UICollectionViewdelegate \ datasouce с UIViewController. Это упрощает управление всеми вашими компонентами.

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

  3. В соответствии с вашим снимком экрана пользовательского интерфейса, я не думаю, что вам нужно взять два UITableView каждый для Всех билетов и Решенных билетов, потому что в определенном пользователе время либо выберите Все билеты или Решенными Билеты. Поэтому возьмите один UITableView и используйте свойство reload tableview и измените данные таблицы.

  4. И вы сделали половину работы с storyboard, и я не думаю, что вам необходимо создать программный код UITableView, потому что ваш UITableView не изменится во время выполнения, просто измените его данные.

Редактировать

Как показывают данные с прокрутки эффекта на пользовательском интерфейсе.

Правильно выбран вариант выбора заголовка.

  1. Для вашего нижнего желтого зрения принять дополнительные UIcollectionView

  2. Set прокрутки свойство UIcollectionView к горизонтальному только.

  3. Создайте UIcollectionViewcell и добавьте в него UITableView.
  4. Ваши UIcollectionViewcell имеют размер вашего желтого вида.
  5. Для поддержания UIcollectionViewcell высоты, вы должны рассчитать свою внутреннюю tableView высоты и размером и UIcollectionViewcell высоты с помощью UICollectionViewDelegateFlowLayoutsizeForItemAtIndexPath; метода.
  6. Используйте пейджинг в collectionView, чтобы получить лучший эффект перетаскивания и правильно обновить данные в соответствии с вашими требованиями.
  7. Чтобы управлять несколькими коллекции в использовании одного класса ниже кода в cellforItem

    if(collectionView == tabCollectionView){ // do code here for the tab collection } else{ // do code here for the data collectionView }

+0

Для точки 1 - №. Я создал свой UITableView программно. Это не часть UICollectionViewCell. UITableView добавляется как подпункт к этому желтому представлению. – appleBoy21

+0

Для точки 2 - насколько это касается ограничений, см. ТаблицуView.translatesAutoresizingMaskIntoConstraints = NO; [_parentViewForTableViews addSubview: tableView]; [_tabRespectiveTableViewsArray replaceObjectAtIndex: indexPath.row withObject: tableView]; в cellForItemAtIndexPath. _parentViewForTableViews - это мое представление, которое вы можете видеть в желтом цвете – appleBoy21

+0

Если ваш табличный вид не является частью коллекции, то почему вы инициализируете представление таблицы в представлении коллекции. Вы можете указать данные загрузки в «CellForItem» methos –

0

Попробуйте это в ячейке для строки на indexPath.

TicketTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; 
      if (cell == nil) 
      { 
       cell = [[TicketTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TicketTableViewCell" owner:self options:nil]; 
       cell = [nib objectAtIndex:0]; 
      } 
+0

Извините, что не работает – appleBoy21

0
 Please follow the below steps 
     1. Create two array. one array will contain the data for all tickets arrAllTickets and another will contain the data for resolved tickets arrResolved 
     2. Drag one table view below two button and give IBOutlet (tblTickets) and delegate and datasource to the your controller 
     3. Drag one tableview cell and give its identifier name for ex : TicketCell 
     4. Create the custom UITableviewCell class TicketCell.h and TicketCell.m file and assign it Cell created in 3rd step. 
     5. Place required control from story board to cell as per your design and give outlet to it in TicketCell.h 
     6. In your controller class in UITableView Delegate method cellForRowAtIndexPath write down below code to place the cell to tableview. 

     -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
     { 
      TicketCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TicketCell"]; 
    Ticket *objTicket=(isAllTicketsSelected)?[arrAllTickets objectAtIndex:indexPath.row]:[arrResolved objectAtIndex:indexPath.row]; 
     [cell.imgProfile sd_setImageWithURL:objTicket.profilePictureURL placeholderImage:[UIImage imageNamed:@"defaultlist"]]; 
     [cell.lblName setText:[objTicket fullName]]; 
     return cell; 
     } 

7. Now take one bool variable isAllTicketsSelected. make isAllTicketsSelected=true when user tap on all tickets isAllTicketsSelected= false when user tap on resolved tickets. after that reload the tableview. 

isAllTicketsSelected = true 
[tblTicket reloadData]; 
+0

Спасибо за сообщение ответа. В основном tou сообщают создать единый UITableView, который загружает данные в зависимости от выбранной вкладки. Но предположим, что вы находитесь на вкладке 1, и вам нужно перейти на вкладку 2 с помощью PanGestureRecognizer. Поэтому, пока вы переходите с вкладки 1 на вкладку 2, считайте, что вы находитесь в промежутке между экраном и хотите видеть данные табличного представления из вкладки 2. Для этого подхода с использованием одного представления таблицы не будет решение – appleBoy21

+0

Вы можете видеть этот эффект в android youtube при панорамировании с одной вкладки на другую – appleBoy21

+0

, в этом случае вы можете использовать Horizontal UIcollectionView с ячейкой. каждая ячейка имеет один вид таблицы. Задайте свойство с включенным пейджингом в значение YES, чтобы иметь эффект без использования жестов. –

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