ipad how to create programmatically multiple tables on one view

前端 未结 3 780
执笔经年
执笔经年 2020-12-10 09:58

i need to create an iPad app where i have to show multiple tables(no grid, just 1 collumn with multiple rows) in one single view. this have to be done programmatically becau

3条回答
  •  旧巷少年郎
    2020-12-10 10:13

    This absolutely can be done.

    Probably the easiest way you can do this is to subclass UITableView, so that each TableView you create can have a unique handler for its delegate and datasource, ala:

    DynamicTableView.h

    @interface DynamicTableView : UITableView  {
        NSMutableArray *items;
    }
    
    @end
    

    DynamicTableView.m

    #import "DynamicTableView.h"
    
    @implementation DynamicTableView
    
    -(id) initWithFrame:(CGRect)frame style:(UITableViewStyle)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)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return [items count];
    }
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
    }
    
    -(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] autorelease];
        }
    
        cell.textLabel.text = [items objectAtIndex:indexPath.row];
    
        return cell;
    }
    
    @end
    

    This is a very simple implementation, that when it's initialized fills its datasource (the items array) with two timestamps. Using it is as simple as something like:

    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];
    }
    

    Modify the DynamicTableView to accept whatever data source you want and how it is displayed.

    Hope that helps!

提交回复
热议问题