2012-04-25 80 views
9

如何在中使用?下面是我想要做的(除了這僅僅是UITableview在我的故事板)的例子:UIViewController中的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; 
} 

delegatedatasource,並UITableView都迷上了我的故事板:

UITableView Delegate and DataSource in Interface Builder Connections Outlet

我不能得到的TableView加載,我告訴它的內容。它總是空白。爲什麼TableView不會填充我在cellForRowAtIndexPath方法中告訴它的內容?我在這裏錯過了什麼?

回答

11

您必須將數據源和代理插座從故事板中的tableview鏈接到視圖控制器。這不是可選的。這就是爲什麼你的表是空白的,它永遠不會調用你的視圖控制器的表視圖方法。 (你可以通過在它們上設置斷點來證明這一點,並且看到它們永遠不會被觸發。)你得到了什麼樣的構建錯誤?

+0

我不再獲得編譯錯誤,但是當我試圖與該表進行交互的應用程序崩潰。 cellForRowAtIndex方法是填充表視圖的正確位置嗎? – 2012-04-29 23:23:37

+0

崩潰時的錯誤信息是什麼?在Objective-C異常中設置一個斷點,以便您可以找出它正在崩潰的線路。 – jsd 2012-04-30 16:10:01

+0

我連接dataSource和委託插座到我的ViewController(正確),我不再會得到構建錯誤或崩潰。當我在cellForRowAtIndexPath和numberOfRowsInSection中設置斷點時,會發現它們,但它們的內容永遠不會執行。此外,它甚至沒有進入cellForRowAtIndexPath,這個方法被忽略。這是爲什麼發生? – 2012-04-30 19:37:41

1

您沒有返回任何有效值。 查看return;沒有任何數值返回?

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

您需要YourTableView一個IBOutlet,然後TableView中連接到YourTableView

相關問題