我正在转换到iOS 5和故事板。当我有一个具有默认单元格样式的表视图时,一切正常。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifierFromStoryboard"];
}
return cell;
}
我见过删除“if(cell == nil)”块的示例。但是,如果我把它拿出来,我的应用程序会崩溃并显示以下消息:“UITableView dataSource必须从tableView返回一个单元格:cellForRowAtIndexPath:”。这不是问题,因为它的工作原理如上所示。
我的问题是我想为单元格使用自定义样式,因此不能使用initWithStyle。如何初始化我在故事板上设计的自定义单元格?
旧的5前应用程序有一个笔尖和类使用类似的东西,但现在我正在使用故事板。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomTableCell *cell = (MyCustomTableCell *) [tableView dequeueReusableCellWithIdentifier:@"MyCustomIdentifier"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomTableCell" owner:self options:nil];
cell = (MyCustomTableCell *) [nib objectAtIndex:0];
}
return cell;
}
答案 0 :(得分:39)
这样
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
return cell;
}
答案 1 :(得分:9)
这对我来说很完美(Xcode 4.5.2和iOS 6.0):
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if( cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
UILabel *title = (UILabel*) [cell viewWithTag:1000];
UILabel *summary = (UILabel*) [cell viewWithTag:1001];
[title setText:[ tableMainTitle objectAtIndex:indexPath.row]];
[summary setText:[ tableSubTitle objectAtIndex:indexPath.row]];
return cell;
}
重要提示:不要忘记设置委托和数据源。
答案 2 :(得分:8)
如果使用以下方法加载包含tableview的视图控制器:
MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
然后在cellForRowAtIndexPath
内你只需要一行:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];
dequeueReusableCellWithIdentifier
将实例化一个单元格(如果不存在)。
答案 3 :(得分:0)
我认为这个效果非常好。我试图让我的头围绕它一段时间并且感谢它工作..好吧我正在做这个,当我试图分配一个单元格时我使用普通的单元格而不是我创建的单元格分配
所以我这样做,所以这就是为什么它不起作用
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
所以代替UITableViewCell用您的类分配单元格,以及上面的示例“CustomCell”
再次感谢
答案 4 :(得分:0)
static NSString *identifier=@"SearchUser";
SearchUserCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell==nil)
{
cell=[[SearchUserCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
return cell;