0

Does anyone have an idea about how to use a single UITableView in multiple ViewControllers?

I need to create a common UITableView for all my view controllers and use it through out the application.

Any help is appreciated.

Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
Shital Tiwari
  • 175
  • 2
  • 3
  • 17
  • 1
    There's a few ways. You need to provide more details about your needs to be able to offset a good suggestion. It would also help if you update your question with some of the ideas you've found so far. – rmaddy May 19 '14 at 06:38
  • @maddy: what my requirement is in my application there is table view which is having same structure in all view controllers. Currently I have added table view in all view controller separately. – Shital Tiwari May 19 '14 at 07:36
  • Why not reuse the same view controller class for each one? You can make a generic view controller that can display different data sets. – rmaddy May 19 '14 at 16:34

2 Answers2

2

Use ContainerView, you can drag ContainerView into your ViewControllers in a storyboard, adjust the size according what you need. You use the ContainerView in all that ViewController that need the TableView.

Attached is a screen shot of one of my app that is using ContainerView that contains a TableView inside the ViewController. I am using the same thing in 2 different ViewControllers.

enter image description here

Ricky
  • 10,485
  • 6
  • 36
  • 49
-1

You can use singleton. Here is an example:

CommonTableView.h file:

#import <Foundation/Foundation.h>

@interface CommonTableView : UITableView <UITableViewDelegate>

+ (CommonTableView *)sharedInstance;

@end

CommonTableView.m file:

#import “CommonTableView.h”

CommonTableView *sharedInstance = nil;

@implementation CommonTableView

+ (CommonTableView *)sharedInstance
{    
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
        sharedInstance = [[super allocWithZone:nil] init];
    });

    return sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.delegate = self;
        //customize your table view
    }

    return self;
}

#pargma mark - UITableView delegate
//…

@end

Then you can access your tableView with [CommonTableView sharedInstance] in the UIViewControllers that you want.

spasbsd
  • 1
  • 1
  • 1
    You can't add a singleton table view to more than one view controller at a time. If you try to add it to a 2nd controller, it will be removed from the 1st one. – rmaddy May 19 '14 at 06:53
  • It is normal. But you don't need to have it in more then one place. If you add the table view in viewWillApear you wont have a problem. I am not a big fan of singletons but this is one of the solutions to this problem. – spasbsd May 19 '14 at 07:43