UITableView within a UIViewController

帅比萌擦擦* 提交于 2019-12-22 04:05:26

问题


How can I use a uitableview inside of a uiviewcontroller? Below is an example of what I'm trying to do (except this is just the UITableview in my Storyboard):

I've figured out that I need to add the delegate and data source to my header:

//MyViewController.h
@interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

In my Implementation file, I've added the required methods:

//MyViewController.m

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"cellForRowAtIndexPath");

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FileCell"];

    NSLog(@"cellForRowAtIndexPath");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *fileListAct = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];

    cell.textLabel.text = [NSString stringWithFormat:@"%@",[fileListAct objectAtIndex:indexPath.row]];

    return cell;
}

The delegate, datasource, and UITableView are all hooked up in my Storyboard:

I can't get the TableView to load the content that I tell it to. It always comes up blank. Why won't the TableView fill with the content I tell it to in the cellForRowAtIndexPath method? What am I missing here?


回答1:


You do have to link the dataSource and delegate outlets from the tableview in storyboard to the view controller. This is not optional. This is why your table is blank, it is never calling your view controller's table view methods. (You can prove this by setting breakpoints on them and seeing that they never get triggered.) What sort of build errors are you getting?




回答2:


You are not returning any valid value. See the return; without any numeric value to return?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return; // it should be return 15; or return self.datasource.count;
  NSLog(@"numberOfRowsInSection");
}



回答3:


You need an IBOutlet for YourTableView, then connect TableView to YourTableView




回答4:


The problem is in the UITableViewDelegate method numberOfRowsInSection. This one does not return an NSInteger number of rows. This example can help:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return theNumberOfRowsForYourTable; // <-- not just return;
}


来源:https://stackoverflow.com/questions/10324744/uitableview-within-a-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!