2012-04-26 68 views
1

假設我有一個帶兩個部分的UITableView。如果該部分的數據源爲空,我想顯示一個佔位符單元格,其文本爲「部分名稱爲空。」UITableView中的佔位符單元格

我該怎麼做?

代碼

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    if(section == 1) 
    { 
     return @"Section One"; 
    } 
    if(section == 0) 
    { 
     return @"Section Two"; 
    } 
    return @""; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (section == 1) 
    { 
     return self.sectionOne.count; 
    } 
    else 
    { 
     return self.sectionTwo.count; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    NSArray *theSource =[[NSArray alloc] init]; 

    if(indexPath.section == 1) 
    { 
     theSource = self.sectionOne; 
    } 
    else 
    { 
     theSource = self.sectionTwo; 
    } 

    // See if there's an existing cell we can reuse 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; 
if (cell == nil) 
    { 
     // No cell to reuse => create a new one 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"]; 
     cell.backgroundView = [[UIImageView alloc] init]; 
     // Continue creating cell 
     } 
    } 
+0

請發佈您已有的代碼! – 2012-04-26 19:56:00

回答

3

實現以下功能在您的UITableViewDataSource(僞代碼):

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (datasource == empty) 
     return 1; 
    else 
     return [datasource count]; 
} 

和:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (datasource == empty) 
     return stub cell; 
    else 
     return regular cell; 
} 
+0

謝謝,效果很好! – 2012-05-01 19:35:24

0

相反,這樣做表視圖中的任何事情;我會檢查數據模型,並可能相應地更新數據模型。

您正在顯示節標題數組中的節標題(我假設);

如果行/記錄存在或不存在,您可以檢查;如果不是,則相應地更新您的節標題數組;

sectionTitleArray = [@"First Section", @"Second Section", @"Third Section"] 

rowValueArray = [[NSArray的 arrayWithObjects:@ 「First1」,@ 「First2」],[NSArray的數組],[NSArray的 arrayWithObjects:@ 「Third1」,@ 「Third3」]

如果([[rowValueArray objectAtIndex:1]計] < 0){

//行是空的對 第二部分; **

然後更新sectionTitleArray

sectionTitleArray = [@ 「第一部分」,@ 「部分爲空」,@ 「第三部分」]

}

它只是一個場景,而不是實際的代碼。