我正在尝试将 2 个 UITableView
添加到我的 UIViewController
。我需要向这些表中添加不同的数据。
这就是我添加 2 个表的方式(此代码已添加到 ViewDidLoad 方法)
self.tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0,140,292,250) style:UITableViewStylePlain] ;
self.tableView2 .dataSource = self;
self.tableView2 .delegate = self;
然后是其他表
self.tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0,0,320,100) style:UITableViewStylePlain] ;
self.tableView1 .dataSource = self;
self.tableView1 .delegate = self;
节数定义如下;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView==tableView1) {
return 12;
}
else { return 10; }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ...... more code here
if (tableView == self.tableView1) {
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text=@"Cells .... ";
}
else{
// the remaining code here.. i am populating the cell as in the previous `IF` condition.
}
}
问题是,我只填充了第一个表格,而不是第二个表格。为什么是这样?我该如何解决这个问题?
编辑: 我还添加了以下代码,希望它有所改变
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView==tableView1) {
return 1;
}
else if (tableView==tableView2) { return 0; }
else { return 0; }
}
最佳答案
尝试按照这些步骤使两个 TableView 具有相同的delegate
和dataSource
。
设置 TableView 的
tag
属性,并为这两个值设置#define
常量。这使代码保持一致。在您在 View Controller 子类中实现的委托(delegate)和数据源方法中,根据您定义的常量测试
tag
属性值。不要为 TableView 返回 0 部分,它根本不会显示任何单元格。
所以,例如:
#define TV_ONE 1
#define TV_TW0 2
// setting the tag property
self.tableView1 = [[UITableView alloc]
initWithFrame:CGRectMake(0,0,320,100)
style:UITableViewStylePlain];
self.tableView1.tag = TV_ONE;
self.tableView1.dataSource = self;
self.tableView1.delegate = self;
// the same for tableView2 using TV_TWO
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView.tag == TV_ONE) {
return 1;
}
else if (tableView.tag == TV_TWO) {
return 1; // at least one section
}
else { return 0; }
}
关于iphone - 将数据添加到 2 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8630135/