【发布时间】:2012-08-06 06:40:08
【问题描述】:
我在UIViewController 中使用了两个UITableViews,如何在两个表格视图中填充行和单元格?当我给第二个表格视图时,它说重复声明部分中的行数等。
【问题讨论】:
标签: iphone xcode uitableview
我在UIViewController 中使用了两个UITableViews,如何在两个表格视图中填充行和单元格?当我给第二个表格视图时,它说重复声明部分中的行数等。
【问题讨论】:
标签: iphone xcode uitableview
这就是为什么 dataSource/delegate 方法有一个tableView 参数的原因。根据其值,您可以返回不同的数字/单元格/...
- (void)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == _myTableViewOutlet1)
return 10;
else
return 20;
}
【讨论】:
tableView 参数。不仅是numberOfRowsInSection,还有cellForRowAtIndexPath或didSelectRowAtIndexPath。
您的所有UITableViewDelegate 和UITableViewDatasource 方法将只实现一次。您只需要检查该方法被调用的是哪个表视图。
if (tableView == tblView1) {
//Implementation for first tableView
}
else {
//Implementation for second tableView
}
这适用于所有 TableView 的委托和数据源方法,因为 tableView 是所有方法中的通用参数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {}
This Link也有你的问题的解决方案。
希望对你有帮助
【讨论】:
请看一下。
首先在界面生成器中创建两个表视图,然后连接两个 IBOutlet 变量并为两个表视图设置委托和数据源。
在接口文件中
-IBOutlet UITableView *tableView1;
-IBOutlet UITableView *tableView2;
在实现文件中
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView==tableView1)
{
return 1;
}
else
{
return 2;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView==tableView1)
{
return 3;
}
else
{
if (section==0)
{
return 2;
}
else
{
return 3;
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView==tableView1)
{
//cell for first table
}
else
{
//cell for second table
}
return cell;
}
使用此代码。希望有帮助
【讨论】:
有可能,看这里的参考代码:http://github.com/vikingosegundo/my-programming-examples
另请参阅此页面:2 tableview on a single view
【讨论】: