tableview iphone中的奇怪行为

时间:2011-06-28 11:44:04

标签: iphone objective-c cocoa-touch uitableview

这有点奇怪。我的应用程序中有一个表视图,显示从数据库中获取的数据。如果我向下滚动并选择一个单元格,文本将会改变,并且来自某个先​​前单元格的一行文本将被放置在当前所选单元格的文本上方。我知道这可能是由于reuseIdentifier,但我不知道如何解决这个问题。这是我正在使用的代码:

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

    UILabel* labelCourse;
    UILabel* labelPlace;

    static NSString *kCellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }

    Course *course = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        course = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    else
    {
        course = [self.courses objectAtIndex:indexPath.row];
    }    


    CGRect labelCourseFrame = CGRectMake(10, 10, 290, 25);
    labelCourse = [[UILabel alloc] initWithFrame:labelCourseFrame];
    labelCourse.font = [UIFont systemFontOfSize:14.0];
    labelCourse.font = [UIFont boldSystemFontOfSize:18];
    [cell.contentView addSubview:labelCourse];

    CGRect labelPlaceFrame = CGRectMake(10, 35, 290, 25);
    labelPlace = [[UILabel alloc] initWithFrame:labelPlaceFrame];
    labelPlace.font = [UIFont systemFontOfSize:12.0];
    labelPlace.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:labelPlace];

    labelCourse.text = course.name;
    labelPlace.text = course.location;

    [labelCourse release];        
    [labelPlace release];
//    cell.textLabel.textColor = [UIColor colorWithHexString:@""];

    return cell;
}

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以将创建部分移动到创建新单元格的if子句中。

if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    CGRect labelCourseFrame = CGRectMake(10, 10, 290, 25);
    labelCourse = [[UILabel alloc] initWithFrame:labelCourseFrame];
    labelCourse.font = [UIFont systemFontOfSize:14.0];
    labelCourse.font = [UIFont boldSystemFontOfSize:18];
    [cell.contentView addSubview:labelCourse];

    CGRect labelPlaceFrame = CGRectMake(10, 35, 290, 25);
    labelPlace = [[UILabel alloc] initWithFrame:labelPlaceFrame];
    labelPlace.font = [UIFont systemFontOfSize:12.0];
    labelPlace.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:labelPlace];

    labelCourse.tag = 50;
    labelPlace.text = 51;

    [labelCourse release];        
    [labelPlace release];
}

如您所见,我已将tag附加到视图中,以便在重复使用单元格时可以检索标签。现在获取标签,

UILabel * labelCourse = [cell viewWithTag:50];
UILabel * labelPlace = [cell viewWithTag:51];

并设置它们,

labelCourse.text = course.name;
labelPlace.text = course.location;    
相关问题