How to add static TableView to ViewController

2019-09-05 18:26发布

How to add static TableView to ViewController without using of a container and UITableViewController?

I think it was possible some time ago but now with latest xCode storyboard and iOS 7 it is not. The similar question without valid answer is here - iOS 7 change UIView to UITableView My table has a little difference - I try to add a static data. And I get an application crash at program start. Program crashes if I set just the datasource. If I unlink the datasource and stay the delegate and outlet the program starts without warnings but with empty cells. A remark - Storyboard changes naming for ViewController from ViewController to TableViewController at view tree without my assistance. I think it occurs after adding an IBOutlet UITableView *myTableView. Why so and what does it mean?

1条回答
冷血范
2楼-- · 2019-09-05 18:53

In the UITableViewDataSource there are 2 required methods :

– tableView:cellForRowAtIndexPath:  required method
– tableView:numberOfRowsInSection:  required method

It means that in MYTableViewController you must implement those like this (example with 3 cells Test1, Test2 and Test3) :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyStaticCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Test%d",indexPath.row+1];
    return cell;
}
查看更多
登录 后发表回答