Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 UITableViews in one UIView

I have a UIView that will need to display two UITableViews, but they are never shown together, by using a SegementedBar you can toggle one or the other.

What would be the best way to handle this? Just create one Table View Controller and change the data source, or create 2 Table View Controllers and just hide one when the other is visible.

The 2 tables will have a completely different layout with different custom cells.

like image 994
woutr_be Avatar asked May 18 '12 08:05

woutr_be


3 Answers

I would keep one datasource & delegate.

This means that all the delegate/datasource methods become more complicated BUT it means that you can retain the one to one relationship between viewController & view.

keep a reference to each of the table views

//vc.h
@property (nonatomic, weak) IBOutlet UITableView* firstTableView;
@property (nonatomic, weak) IBOutlet UITableView* secondTableView;

In the datasource/ delegate methods you need to account for the fact that the method needs to behave differently depending on which table view is in use. e.g.

//vc.m
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    if (tableView == self.firstTableView) {

        ...

    } else { // tableView == self.secondTableView

        ...
    }
}

return cell;

}

like image 168
Damo Avatar answered Oct 22 '22 22:10

Damo


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    if (tableView.tag == 1) {

        ...

    } else { // tableView == self.secondTableView

        ...
    }
}

tag could be assigned from the .xib. so no need to have UITableVeiw variable in .h file. Two table view in .xib needed

like image 26
Warif Akhand Rishi Avatar answered Oct 22 '22 21:10

Warif Akhand Rishi


Both approach has some pros and cons, but i will personally prefer approach having two separate controller.

Approach 1 - create one Table View Controller and change the data source

  • This approach help in avoiding extra and repeated code.
  • With this memory management is good as using one controller only.(Although this is not a big concern till then we won't have a lot of data.)
  • Issue with this is having complexity.

Approach 2 - 2 Table View Controller

  • With this approach definitely have extra and repeated code.
  • But with this is less complexity.
like image 4
rishi Avatar answered Oct 22 '22 22:10

rishi