iostableviewuitableviewloadview

iOS programmatic grouped table empty


I have a programmatically implemented tableView, in the grouped style.

All I am getting is the gray pinstripes when it should be populated. So it is loading, but not ... something...

What more is necessary? If no more, then where else ought I look?

Also, how can I make the background color of the table the same as the cell's white color?

- (void)loadView {

    [super loadView];

    UITableView *view = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame style:UITableViewStyleGrouped];

    [view setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];

    self.view = view;

    [view reloadData];

}

Is viewDidLoad necessary?

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

Thank you,


Solution

  • You have to provide your tableView with data.

    For staters you'll need to define a dataSource. Its common to just use your viewController as the dataSource.

    // in the .h find something similar and add <UITableViewDataSource>
    @interface ViewController : UIViewController <UITableViewDataSource>
    

    then when you make the tableView.

    view.datasource = self;
    

    Then you'll need to provide the data itself. Implement these methods:

    #pragma mark - UITableView Datasource
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 3;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 3;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    
        [cell.textLabel setText:@"A Cell"];
    
        return cell;
    }
    

    Those methods will create 3 sections each with 3 rows. All the cells will just say A Cell. This is the basis for all tableViews. Just customize the data :)