TERACytE
TERACytE

Reputation: 7863

How to programmatically assign/replace an existing UITableView with a new one?

I have the following code to my UIViewController class implementation:

- (void)viewDidLoad {
    CustomUITableView *customUITableView = [[CustomUITableView alloc] initWithFrame:self.view.frame];        
    [self.view addSubview:customUITableView];    
    [super viewDidLoad];
}

When I run the app, the table shows up just fine. There are two problems I have with this approach:

  1. I lose the use of StoryBoard since the table is dynamically added to the view. I would like to arrange my view in StoryBoard and not have to manually tweak its position in code.
  2. I also want the ability to swap between CustomUITableViews at runtime (if possible). For example, if I create a "CustomUITableView_Number2", can I simply decide which custom class I want to use for the table at runtime?

I know I can accomplish this in StoryBoard by assigning a custom class to the UITableView, but I want to see how far I can go using only code. My goal is to arrange the layout using StoryBoard, but assign the custom class I want at runtime.

Does anyone know if this is possible? Sample code would really help. Thank-you.

Upvotes: 0

Views: 517

Answers (2)

drunknbass
drunknbass

Reputation: 1672

sure you can replace the table. something as simple as

Class MyTableClass = NSClassFromString(@"WhateverClass");
    id newTableView = [[MyTableClass alloc] init];
    [newTableView performSelector:@selector(someSel:)];

make sure you set your datasource and delegate and whatever properties from the original nib instantiated view first, then you could then set your local tableview property to this new object and as long as the ivar has a proper cast you could call methods on it without resorting to runtime calls like above.

You can also dig into the obj-c runtime if you wanted to do it in a different way. https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

Upvotes: 0

Joel Kravets
Joel Kravets

Reputation: 2471

You could load a regular UITableView from interface builder and then initialize a CustomUITableView with the parameters you are interested in from the UITableView.

- (void)viewDidLoad {

    //Your tableView was already loaded
    CustomUITableView *customUITableView = [[CustomUITableView alloc] initWithFrame:tableView.frame style:tableView.style];   
    customUITableView.backgroundColor = tableView.backgroundColor;
    //...
    //... And any other properties you are interested in keeping 
    //...    
    [self.view addSubview:customUITableView];    
    [super viewDidLoad];
}

This approach will work if you make sure to specify each property you think you would modify in interface builder. Just make sure to remove the UITableView that was loaded via the nib after you copy the properties over.

Upvotes: 1

Related Questions