2013-03-06 23 views
0


我正在创建一个通用的iPhone/iPad应用程序,我希望在主视图上具有自定义单元格。它适用于iPhone,但在iPad上dequeueReusableCellWithIdentifier:返回nil而不是单元格。下面是一些我的代码(我代替我自定义的细胞与正常的UITableViewCell,因为它不反正工作):iOS通用应用程序 - 自定义UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier; 

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { 
     CellIdentifier = @"MainPadCell"; //works fine when replaced with MainPhoneCell 
     __weak UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //returns nil 

     [cell.textLabel setText:@"Test"]; 

     return cell; //crash 
    }else{ 
     CellIdentifier = @"MainPhoneCell"; 
     __weak UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

     [cell.textLabel setText:[NSString stringWithFormat:@"Cell %i", indexPath.row]]; 

     return cell; 
    } 
} 

奇怪的是,当我与MainPhoneCell取代MainPadCell细胞则显示手机电池(虽然我在我的iPad Storyboard中没有任何MainPhoneCell重用标识符,我在iPad故事板中有MainPadCell,但无法找到它)。
感谢您的任何建议!

+0

我已经解决了这个问题,此代码的工作很好,谢谢大家的前瞻性和应答。 – haluzak 2013-03-06 10:54:44

+0

检查,看是否有用户在iPhone或iPad中的cellForRowAtIndexPath是一个做事的真正低效的方式。只要显示单元格,此方法就会触发。潜在的数千次。 – 2013-03-06 11:26:07

回答

2

重用标识符需要如果要使用两个相同的控制器是相同的。您可以选择具有在iPad TableViewCell多个对象(标签等),并可以在iPad电池不同布局的事情了,但子类TableViewCell(如果你是子类的话)和再利用标识必须为iPhone和相同iPad兼容。

确保还需连接起来的细胞,细胞的物体(同样,如果你是子类)和TableView中委托和数据源出口到VC你的子类。

链接到样本项目展示了如何使用相同的sublcass和重用ID: https://dl.dropbox.com/u/3660978/UniversalTableView.zip

+0

您好,感谢,但重用标识符不需要,因为我使用的是2个不同的故事板,我可以设置2个不同的重用标识符和检查,如果我在iPad或iPhone上,因为我做的是一样的。我终于找到了问题,它完全在其他地方,我上面写的代码工作得非常好。谢谢你的时间,但! – haluzak 2013-03-06 10:54:13

+0

为什么要检查一个不同的重用标识符?你意识到,如果你在cellForRowAtIndexPath中这样做,每当你滚动并显示一个单元格时,它会触发?我刚刚完成了一个示例项目,向您展示我的意思是使用相同的重用标识符。我更新了答案并提供了一个链接到压缩的项目。 – 2013-03-06 11:24:21

+0

是的,你说得对,我只是测试,并没有意识到这一点,谢谢指点出来:) – haluzak 2013-03-06 11:30:10