在XIB中使用多个UITableView

时间:2015-02-14 06:30:54

标签: ios uitableview swift xib ibinspectable

我创建了一个自定义小部件作为XIB文件,其中我有多个UITableView和一个UIButton。在相应的swift文件中,这是这个XIB的所有者,我有这些TableViews的出口。

我已将此小部件添加到UIViewController中视图内的视图中。现在,在此控制器的相应swift文件中,我需要为每个tableviews分配dataSourcedelegate,并为该按钮分配一个动作。

我一直在网上寻找很长时间,似乎@IBInspectable var是可行的方式,但似乎我无法创建类型UITableView,{{{ 1}}或UITableViewDelegateUITableViewDatasource

那么如何使用tableviews和按钮?任何人都可以指导我找到正确的文档,示例或解释吗?

1 个答案:

答案 0 :(得分:1)

无需使用@IBInspectable。您可以有条件地在UITableViewDelegate方法中使用每个表源。这是实现此目的的一种方法:

首先在你的故事板UITableViewController中添加一个原型单元格,然后在该原型单元格中添加一个UITableView及其自己的原型单元格。

然后设置内部和外部表格视图单元格的重用标识符,如下所示:

外表视图单元格: Outer table view cell reuse identifier

内部表格视图单元格: Inner table view cell reuse identifier

然后链接内部tableview的数据源并委托给UITableViewController自己的数据源和委托:

Link data source and delegate #1 Link data source and delegate #2

然后在UITableViewController课程中,您可以设置表格'元素有条件地,例如:

- (void)viewDidLoad {
    [super viewDidLoad];
    dataSource1 = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];
    dataSource2 = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return 80;
    } else {
        return 20;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (tableView == self.tableView) {
        return dataSource1.count;
    } else {
        return dataSource2.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell;

    if (tableView == self.tableView) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier2" forIndexPath:indexPath];
    }

    // Configure the cell...
    if (tableView == self.tableView) {
        cell.textLabel.text = [dataSource1 objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [dataSource2 objectAtIndex:indexPath.row];
        cell.backgroundColor = [UIColor blueColor];
    }
    cell.textLabel.backgroundColor = [UIColor clearColor];

    return cell;
}

在这种情况下会产生以下结果: Final result

相关问题