Fails to call delegate/datasource methods in UITableView implementation

后端 未结 2 1820
温柔的废话
温柔的废话 2020-12-22 05:45

I have created .h and .m files for UITableView called mainTableViewgm.h and mainTableViewgm.m resp. and I am calling -initWithFr

2条回答
  •  礼貌的吻别
    2020-12-22 06:26

    Your tableview is not loaded when the controller is initializing, so you cannot do that in the init methods. You have to move your code to the viewDidLoad method.

    Also you are not setting the delegate and datasource on the tableview object (probably a type, you are setting them on the view controller). It should look like this:

    - (void)viewDidLoad:(BOOL)animated {
        [super viewDidLoad:animated];
        [self.tableView setDelegate:self];
        [self.tableView setDataSource:self]; // <- This will trigger the tableview to (re)load it's data
    }
    

    Next thing is to implement the UITableViewDataSource methods correctly. UITableViewCell *cellOne =[[UITableViewCell alloc] init]; is not returning a valid cell object. You should use at least initWithStyle:. And take a look how to use dequeueReusableCellWithIdentifier:forIndexPath:. A typical implementation would look like this:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
    
        // Reuse/create cell    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
    
        // Update cell contents
        cell.textLabel.text = @"Your text here";
        cell.detailTextLabel.text=@"text did appear";
    
        return cell;
    }
    

提交回复
热议问题