IOS: tableview delegate methods for two tableview

前端 未结 4 853
暗喜
暗喜 2020-12-31 20:28

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

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

- (NSInteger)ta         


        
相关标签:
4条回答
  • 2020-12-31 21:11

    Each of those methods passes in a reference to the table view that's calling it. I usually connect each table to an outlet in interface builder and conditionally return the datasource based on a comparison with tableView in the delegate methods and the outlet names. Doing so with a tag is also possible but messier and more open to complications when editing your view structure.

    0 讨论(0)
  • 2020-12-31 21:23

    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.

    0 讨论(0)
  • 2020-12-31 21:25

    Yes you can do it with tag. Give your UITableViews the tags 1 and 2.

    set up an switch:

    - (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] ; 
    }
    
    switch ([tableView tag]) {
      case 1:{
        [[cell textLabel] setText:@"First tag"]
        break;
      }
      case 2:{
        [[cell textLabel] setText:@"Second tag"]
        break;
      }
      default:
        break;
    }
    
    return cell;
    }
    
    0 讨论(0)
  • 2020-12-31 21:26

    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;
    }
    
    0 讨论(0)
提交回复
热议问题