OGeek|极客世界-中国程序员成长平台

标题: ios - ipad如何在一个 View 上以编程方式创建多个表 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:28
标题: ios - ipad如何在一个 View 上以编程方式创建多个表

我需要创建一个 iPad 应用程序,我必须在一个 View 中显示多个表格(没有网格,只有 1 个多行列)。这必须以编程方式完成,因为在后台有人要设置该数量的表。

View 会有一个滚动条,所以我可以看到所有这些。

这可以做对吗?

有人可以提供我的一些代码或链接到一些关于如何在一个 View 中创建 N 个表的教程,以便随时定位它们。



Best Answer-推荐答案


这绝对可以做到。

您可以做到这一点的最简单的方法可能是继承 UITableView,这样您创建的每个 TableView 都可以为其委托(delegate)和数据源拥有一个唯一的处理程序,ala:

DynamicTableView.h

@interface DynamicTableView : UITableView <UITableViewDelegate, UITableViewDataSource> {
    NSMutableArray *items;
}

@end

DynamicTableView.m

#import "DynamicTableView.h"

@implementation DynamicTableView

-(id) initWithFrameCGRect)frame styleUITableViewStyle)style {
    if (self == [super initWithFrame:frame style:style]) {
        items = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat"%i", [NSDate timeIntervalSinceReferenceDate]],
                 [NSString stringWithFormat"%i", [NSDate timeIntervalSinceReferenceDate]], nil];
    }

    return self;
}

-(void) dealloc {
    [items release];

    [super dealloc];
}

-(NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section {
    return [items count];
}

-(NSInteger)numberOfSectionsInTableViewUITableView *)tableView {
    return 1;
}

-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [items objectAtIndex:indexPath.row];

    return cell;
}

@end

这是一个非常简单的实现,它在初始化时用两个时间戳填充它的数据源(items 数组)。使用它就像这样简单:

for (int i = 0; i < 4; i++) {
    DynamicTableView *table = [[[DynamicTableView alloc] initWithFrame:CGRectMake(10, (i * 100) + 10, 200, 50) style:UITableViewStylePlain] autorelease];
    [table setDelegate:table];
    [table setDataSource:table];

    [self.view addSubview:table];
}

修改 DynamicTableView 以接受您想要的任何数据源及其显示方式。

希望有帮助!

关于ios - ipad如何在一个 View 上以编程方式创建多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8066144/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4