dequeueReusableCellWithIdentifier:始终为可见单元格返回'nil'

时间:2011-09-27 10:36:08

标签: iphone uitableview

我创建了一个自定义表格视图单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITextField *editField=nil;
...

NSString *CellIdentifier = [NSString  stringWithFormat:@"cell:%d",indexPath.row];

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    // Configure the cell...
    switch (indexPath.row) {

        case 0: 
        {

            cell.textLabel.text=DEVNAME_TEXT_NDVC;
            cell.textLabel.font=[UIFont boldSystemFontOfSize:LABEL_TEXTSIZE_NDVC];

            editField=[[UITextField alloc] initWithFrame:CGRectMake(158, 9, cell.frame.size.width-183, cell.frame.size.height-15) ];
            editField.tag=DEVNAME_TAG_NDVC;
            ...
            [cell.contentView addSubview:editField ];
            [editField release];

        }
        break;

该表只有5行,每个都在屏幕上。 后来,当我试图访问单元格时,我总是得到'nil'

当用户点击单元格时,以下代码应将光标放置到适当的UITextField,但它不会,因为'cell'始终为= 0.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
NSString *CellIdentifier = [NSString stringWithFormat:@"cell:%d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *tf=nil;

[tableView deselectRowAtIndexPath: indexPath animated: YES];
[activeField resignFirstResponder]; // Last used UITextField

switch (indexPath.row) {
    case 0: //
        tf=(UITextField*)[cell.contentView viewWithTag:DEVNAME_TAG_NDVC];
        [tf becomeFirstResponder]; // Show the keyboard
        //[tf performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.7];
    break;

拜托,你能告诉我哪里错了吗?为什么[tableView dequeueReusableCellWithIdentifier:CellIdentifier]总是= 0, 但所有表格单元格始终可见。

感谢。

3 个答案:

答案 0 :(得分:4)

也许我不理解这个问题,但是一旦表格单元格不再显示,它们是否只能重复使用?如果它们仍然可见,您如何重复使用它们?

答案 1 :(得分:3)

改变这个:

NSString *CellIdentifier = [NSString  stringWithFormat:@"cell:%d",indexPath.row];

为:

static NSString *CellIdentifier = @“XXXX”;

答案 2 :(得分:1)

是的,dequeueReusableCellWithIdentifier:始终使用nil返回registerNib:forCellReuseIdentifier:除外。