iphone - 将数据添加到 2 个表

标签 iphone objective-c ios uitableview

我正在尝试将 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 具有相同的delegatedataSource

  1. 设置 TableView 的 tag 属性,并为这两个值设置 #define 常量。这使代码保持一致。

  2. 在您在 View Controller 子类中实现的委托(delegate)和数据源方法中,根据您定义的常量测试 tag 属性值。

  3. 不要为 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/

相关文章:

ios - objc_exception_throw/崩溃/堆栈跟踪

ios - 数据更改后刷新 View

ios - 如何检查 AVPlayer 的状态?

iphone - 如何在 iOS 上获取 Facebook 访问 token

ios - 导航栏在取消 "Add to Exsting Contact" Controller 时消失

ios - 无法使用 DDMathParser 求解数学表达式

iphone - 类别,协议(protocol),一大类?我应该在这里使用什么

ios - 如何在 iphone sdk 中获取 Vfr Reader for Pdf 的目录?

ios - 使用 Xcode 5.1.1 构建您的应用程序

objective-c - "float_t"是做什么用的?