How to display the UITableView programmatically?

前端 未结 4 1222
温柔的废话
温柔的废话 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
    2020-12-13 15:03

    Maybe its also helpful for you all who new in there.

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // init table view
        tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
        //or, you may do that 
        //tableView = [[UITableView alloc] init];
        //tableView.frame = CGRectMake:(5 , 5 , 320 , 300);
    
        // must set delegate & dataSource, otherwise the the table will be empty and not responsive
        tableView.delegate = self;
        tableView.dataSource = self;
    
        tableView.backgroundColor = [UIColor cyanColor];
    
        // add to canvas
        [self.view addSubview:tableView];
    }
    
    #pragma mark - UITableViewDataSource
    // number of section(s), now I assume there is only 1 section
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
    {
        return 1;
    }
    
    // number of row in the section, I assume there is only 1 row
    - (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
    {
        return 1;
    }
    
    // the cell will be returned to the tableView
    - (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"HistoryCell";
    
        // Similar to UITableViewCell, but 
        JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        // Just want to test, so I hardcode the data
        cell.descriptionLabel.text = @"Testing";
    
        return cell;
    }
    
    @end
    

提交回复
热议问题