2012-04-26 67 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 = [@ “第一部分”,@ “部分为空”,@ “第三部分”]

}

它只是一个场景,而不是实际的代码。