Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two tables in the same class, I need each table contains different data but i have a trouble with the delegate... How can make each table contains a separate delegate? Thanks, sorry for my English.

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

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

    return [dataTable1 count];
     }

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


    CeldaFamilia *cell = (CeldaFamilia *)[aTableView dequeueReusableCellWithIdentifier:@"CeldaFamilia"];




    if (!cell) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CeldaFamilia" owner:self options:nil];
        cell = [nib objectAtIndex:0];

    }

    cell.propTextFamilia.text =[dataTable1 objectAtIndex:indexPath.row];

    return cell;
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this by looking at the tableView argument that was passed in. Example:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView1) {
        return [dataTable1 count];
    } else /* tableView == self.tableView2 */ {
        return [dataTable2 count];
    }
}

With this pattern, you need to put if statements in all of your UITableViewDataSource and UITableViewDelegate methods.

Another way to do it is to make one method that returns the array of data for the table view:

- (NSArray *)dataTableForTableView:(UITableView *)tableView {
    if (tableView == self.tableView1) {
        return dataTable1;
    } else /* tableView == self.tableView2 */ {
        return dataTable2;
    }
}

Then use that function in each of your data source/delegate methods. Example:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self dataTableForTableView:tableView] count];
}

Your tableView:cellForRowAtIndexPath: method might still need to have an if statement, depending on what the data looks like for each table.

However, I recommend you don't use either of those patterns. Your code will be better organized and easier to understand if you make a separate data source/delegate for each table view. You can use two instances of the same class, or you can make two different classes and use one instance of each class, depending on your needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...