在UIViewController中使用UITableView

9
我该如何在中使用?下面是我尝试做的事情的示例(除了这只是我故事板中的UITableview):

UITableView inside a UIViewController

我已经明白我需要将委托和数据源添加到我的头部:
//MyViewController.h
@interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

在我的实现文件中,我已经添加了所需的方法:
//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;
}

在我的Storyboard中,delegatedatasourceUITableView都已连接。

UITableView Delegate and DataSource in Interface Builder Connections Outlet

我无法让TableView加载我告诉它的内容。它总是空白的。为什么TableView不会用cellForRowAtIndexPath方法中告诉它的内容填充呢?我错过了什么吗?
4个回答

11

您需要将Storyboard中TableView的dataSource和delegate与ViewController连接起来,这不是可选项。这就是为什么您的表格是空白的原因,它从未调用您的视图控制器的TableView方法。(您可以通过在它们上设置断点并查看它们是否被触发来证明这一点。)您遇到了什么构建错误?


我不再收到构建错误,但当我尝试与表格交互时,应用程序崩溃了。而cellForRowAtIndex方法是填充表视图的正确位置吗? - Sam Spencer
当程序崩溃时,会显示什么错误信息?在Objective-C异常上设置一个断点,这样你就可以找出它崩溃的行数了。 - jsd
我已经正确地将dataSource和delegate插座连接到了我的ViewController,不再出现构建错误或崩溃。当我在cellForRowAtIndexPath和numberOfRowsInSection处设置断点时,它们被找到,但它们的内容从未执行过。而且,它甚至没有进入cellForRowAtIndexPath,这个方法被忽略了。为什么会发生这种情况? - Sam Spencer
3
如果那些方法没有被调用,那是因为委托和数据源的连接不正确。 - jsd

1
您没有返回任何有效值。 看到没有任何数字值可返回的return;吗?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return; // it should be return 15; or return self.datasource.count;
  NSLog(@"numberOfRowsInSection");
}

0
你需要一个IBOutlet来连接你的TableView,然后将TableView连接到YourTableView。

0
问题在于UITableViewDelegate方法numberOfRowsInSection中。它没有返回NSInteger行数。这个例子可以帮助:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return theNumberOfRowsForYourTable; // <-- not just return;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接