Creating a UITableView Programmatically

后端 未结 9 2209
梦谈多话
梦谈多话 2021-01-31 14:26

I have an application in Xcode 4.6 which uses storyboards. I added a UITableView to a view controller class, which worked as expected. However, when I tried deleting the UITable

9条回答
  •  耶瑟儿~
    2021-01-31 15:07

    You might be do that its works 100% .

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // init table view
        tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
        // 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;
    }
    
    #pragma mark - UITableViewDelegate
    // when user tap the row, what action you want to perform
    - (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSLog(@"selected %d row", indexPath.row);
    }
    
    @end
    

提交回复
热议问题