How to display the UITableView programmatically?

前端 未结 4 1220
温柔的废话
温柔的废话 2020-12-13 14:15

I want to ask a question about the UITableView of the objective C. I am writing a program and I would like to create the UI programmatically. However, I don\'t know how to d

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 15:11

    • Create a new class that inherits from UIViewController.
    • Make it conform to the UITableViewDataSource protocol.
    • Declare your table view.

    Your header file should be like the following:

    @interface MyViewController : UIViewController  {    
    
    }
    
    @property (nonatomic, retain) UITableView *tableView;
    
    @end
    

    In the viewLoad method of your class:

    • Create a table view using initWithFrame. Use dimensions 320x460 for full height. Remove 44 from height if you have a navigation bar and 49 if you have a tab bar.
    • Create a new view.
    • Add the table view to the new view.
    • Set the controller view to the new view.
    • Set the table view data source to your instance (self).
    • Implement the two required data source methods: tableView:cellForRowAtIndexPath and tableView:numberOfRowsInSection

    Your implementation file should be like the following:

    #import "MyViewController.h"
    
    @implementation MyViewController
    
    @synthesize tableView=_tableView;
    
    - (void)dealloc
    {
        [_tableView release];
    
        [super dealloc];
    }
    
    #pragma mark - View lifecycle
    
    - (void)loadView
    {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0) style:UITableViewStylePlain];
        self.tableView = tableView;
        [tableView release];    
    
        UIView *view = [[UIView alloc] init];
        [view addSubview:self.tableView];
        self.view = view;
        [view release];
    
        self.tableView.dataSource = self;
    }
    
    - (void)viewDidUnload {
        self.tableView = nil;
    
        [super viewDidUnload];
    }
    
    #pragma mark - Table view data source
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *MyCellIdentifier = @"MyCellIdentifier";
    
        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
    
        if(cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier] autorelease];
        }
    
        return cell;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
       return 5;
    }
    
    @end
    

提交回复
热议问题