Multiple UITableViews on one UIView

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

I need to have two UITableViews on one UIView. I can make it work with one, here is the code:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {      return 1; }  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {     return [contentOne count];  // sets row count to number of items in array }  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {      static NSString *CellIdentifier = @"Cell";      UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];     if (cell == nil) {         cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];     }      NSString *firstValue = [[NSString alloc] initWithFormat: @"Row %i% %", indexPath.row+1 ];     NSString *secondValue = [contentOne objectAtIndex:indexPath.row];      NSString *cellValue = [firstValue stringByAppendingString: secondValue]; // appends two strings      [cell.textLabel setText:cellValue];        return cell; }  - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {  } 

I have tried several different methods. Anyone? If I could name each UITableView a different name that should do it but it will not let me edit tableView to anything else without crashing.

回答1:

so you need some way to tell the two tableViews apart--you could either set the "tag" property to different values, or have a property on your view controller that points to each view

@property (nonatomic, retain) IBOutlet UITableView *tableView1; @property (nonatomic, retain) IBOutlet UITableView *tableView2; 

then hook these up to each view in interface builder...

then in your view controller methods you can do

(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {     if (tableView == self.tableView1) {         return 37;     } else if (tableView == self.tableView2) {         return 19;     } else {         // shouldn't get here, use an assert to check for this if you'd like     } } 


回答2:

Probably the easiest way of implementing this is to have two delegate and data source classes, one for each table view. That would reduce the number of if (tableview == tableview1) occurances in the view controller code.



回答3:

This sample code might help you...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!