Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: tableview delegate methods for two tableview

I have these delegate method for a tableview inside a class:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [array1 count];
}

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


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
}

cell.textLabel.text = [array1 objectAtIndex:indexPath.row];

return cell;
}

if I have a single UITableView it's ok but if I have two UITableView? How Can I organize my code? with tag?

like image 336
cyclingIsBetter Avatar asked Jun 29 '11 11:06

cyclingIsBetter


2 Answers

See how all the delegate methods have a tableView:(UITableView *)tableView in them?

You can define your table views in the header file and then just simply go: (assuming your table is called myTable)

if (tableView == myTable)

Then you can have as many table views as you like.

So for example:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [array1 count];
}

Becomes:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == myTable)
    {
       return [array1 count];
    }
    if (tableView == myTable2)
    {
       return [array2 count];
    }

    return 0;
}
like image 195
Pripyat Avatar answered Nov 06 '22 14:11

Pripyat


My suggestion is having your data source act as a table view delegate, instead of your controller.

This is a design more closer to the Model-View-Controller pattern and will allow you much more flexibility and avoid checking for the specific value that the tableView argument has got in your delegate methods.

In your case, your delegate/data source would be a class with a member of type NSArray and also implementing the UITableViewDelegate protocol.

like image 22
sergio Avatar answered Nov 06 '22 15:11

sergio