将子视图添加到UITableViewCells会导致滚动时出现问题

时间:2013-03-03 16:15:06

标签: objective-c xcode uitableview addsubview

我对如何解决这个问题感到非常难过。 所以我有一个UITableView和委托方法cellForRowAtIndex:如果单元格是nil(表视图的初始构建),我将向每个单元格添加几个子视图。一切都运行良好,表视图已构建,但是,当我在应用程序中向下滚动一点时,应用程序突然崩溃与SIGBART并给我错误 * 由于未捕获的异常'NSInvalidArgumentException'而终止应用,原因:'+ [NSIndexPath setImage:]:无法识别的选择器发送到类0x3c361e68' * *这很奇怪,因为我甚至没有在我的代码中的任何地方调用setImage方法。 这是委托方法的代码。

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


static NSString *CellIdentifier = @"Cell";
UIImageView* imageView;
UILabel* ttitle;
UILabel* ttitle2;
UILabel* ttitle3;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    // Configure cell:
    // *** This section should configure the cell to a state independent of
    //  whatever row or section the cell is in, since it is only executed
    //  once when the cell is first created.


    imageView=[[UIImageView alloc]initWithFrame:CGRectMake(10.0, 11.0, 50.0, 50.0)];
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    imageView.layer.masksToBounds=YES;
    imageView.layer.cornerRadius=5.0;
    [cell.contentView addSubview:imageView];

    ttitle = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 7.0, 200, 20)] autorelease];
    ttitle.textColor= [UIColor blackColor];
    ttitle.numberOfLines=1;
    ttitle.backgroundColor=[UIColor clearColor];
    ttitle.font=[UIFont fontWithName:@"Arial Bold" size:15.0];
    [cell.contentView addSubview:ttitle];

    if (indexPath.row==0) {

        CGSize size=[[[data objectAtIndex:indexPath.row] valueForKey:@"content"] sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        ttitle2 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 27.5, 200, size.height)] autorelease];
        ttitle2.textColor= [UIColor darkGrayColor];
        ttitle2.backgroundColor=[UIColor clearColor];
        ttitle2.numberOfLines=0;
        ttitle2.textAlignment = NSTextAlignmentLeft;
        ttitle2.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle2.font=[UIFont fontWithName:@"Arial" size:14.0];
        [cell.contentView addSubview:ttitle2];

        ttitle3 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, ttitle2.frame.origin.y+ttitle2.frame.size.height-8.0, 210, 40)] autorelease];
        ttitle3.textColor= [UIColor darkGrayColor];
        ttitle3.backgroundColor=[UIColor clearColor];
        ttitle3.numberOfLines=1;
        ttitle3.textAlignment = NSTextAlignmentLeft;
        ttitle3.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle3.font=[UIFont fontWithName:@"Arial" size:11.0];
        [cell.contentView addSubview:ttitle3];


    }
    else{

        CGSize size=[[[data objectAtIndex:indexPath.row] valueForKey:@"content"] sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        ttitle2 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 27.0, 200, size.height)] autorelease];
        ttitle2.textColor= [UIColor darkGrayColor];
        ttitle2.backgroundColor=[UIColor clearColor];
        ttitle2.numberOfLines=0;
        ttitle2.textAlignment = NSTextAlignmentLeft;
        ttitle2.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle2.font=[UIFont fontWithName:@"Arial" size:14.0];
        [cell.contentView addSubview:ttitle2];


        ttitle3 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, ttitle2.frame.origin.y+ttitle2.frame.size.height-9.0, 210, 40)] autorelease];
        ttitle3.textColor= [UIColor darkGrayColor];
        ttitle3.backgroundColor=[UIColor clearColor];
        ttitle3.numberOfLines=1;
        ttitle3.textAlignment = NSTextAlignmentLeft;
        ttitle3.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle3.font=[UIFont fontWithName:@"Arial" size:11.0];
        [cell.contentView addSubview:ttitle3];

    }

}

// Customize cell:
// *** This section should customize the cell depending on what row or section
//  is passed in indexPath, since this is executed every time this delegate method
//  is called.
imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[data objectAtIndex:indexPath.row] valueForKey:@"thumbnail"]]]];

[ttitle setText:[[data objectAtIndex:indexPath.row] valueForKey:@"name"]];
[ttitle2 setText:[[data objectAtIndex:indexPath.row] valueForKey:@"content"]];

NSString* first=[[[data objectAtIndex:indexPath.row] valueForKey:@"hashtag"] stringByAppendingString:@"     "];
NSString* second =[first stringByAppendingString:[[data objectAtIndex:indexPath.row] valueForKey:@"place"]];
NSString* third=[second stringByAppendingString:@"        "];
NSString* fourth=[third stringByAppendingString:@"¤ "];
NSString* conversion=[[[data objectAtIndex:indexPath.row] valueForKey:@"counter"] stringValue];
NSString* fifth=[fourth stringByAppendingString:conversion];
[ttitle3 setText:fifth];





return cell;

}

感谢帮助人员!

*更新代码

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


static NSString *CellIdentifier = @"Cell";
UIImageView* imageView;
UILabel* ttitle;
UILabel* ttitle2;
UILabel* ttitle3;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    // Configure cell:
    // *** This section should configure the cell to a state independent of
    //  whatever row or section the cell is in, since it is only executed
    //  once when the cell is first created.


    imageView=[[UIImageView alloc]initWithFrame:CGRectMake(10.0, 11.0, 50.0, 50.0)];
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    imageView.layer.masksToBounds=YES;
    imageView.layer.cornerRadius=5.0;
    imageView.tag=1;
    [cell.contentView addSubview:imageView];

    ttitle = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 7.0, 200, 20)] autorelease];
    ttitle.textColor= [UIColor blackColor];
    ttitle.numberOfLines=1;
    ttitle.tag=69;
    ttitle.backgroundColor=[UIColor clearColor];
    ttitle.font=[UIFont fontWithName:@"Arial Bold" size:15.0];
    [cell.contentView addSubview:ttitle];

    if (indexPath.row==0) {

        CGSize size=[[[data objectAtIndex:indexPath.row] valueForKey:@"content"] sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        ttitle2 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 27.5, 200, size.height)] autorelease];
        ttitle2.textColor= [UIColor darkGrayColor];
        ttitle2.backgroundColor=[UIColor clearColor];
        ttitle2.numberOfLines=0;
        ttitle2.tag=70;
        ttitle2.textAlignment = NSTextAlignmentLeft;
        ttitle2.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle2.font=[UIFont fontWithName:@"Arial" size:14.0];
        [cell.contentView addSubview:ttitle2];

        ttitle3 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, ttitle2.frame.origin.y+ttitle2.frame.size.height-8.0, 210, 40)] autorelease];
        ttitle3.textColor= [UIColor darkGrayColor];
        ttitle3.backgroundColor=[UIColor clearColor];
        ttitle3.numberOfLines=1;
        ttitle3.tag=71;
        ttitle3.textAlignment = NSTextAlignmentLeft;
        ttitle3.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle3.font=[UIFont fontWithName:@"Arial" size:11.0];
        [cell.contentView addSubview:ttitle3];


    }
    else{

        CGSize size=[[[data objectAtIndex:indexPath.row] valueForKey:@"content"] sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        ttitle2 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, 27.0, 200, size.height)] autorelease];
        ttitle2.textColor= [UIColor darkGrayColor];
        ttitle2.backgroundColor=[UIColor clearColor];
        ttitle2.numberOfLines=0;
        ttitle2.tag=70;
        ttitle2.textAlignment = NSTextAlignmentLeft;
        ttitle2.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle2.font=[UIFont fontWithName:@"Arial" size:14.0];
        [cell.contentView addSubview:ttitle2];


        ttitle3 = [[[UILabel alloc] initWithFrame:CGRectMake(70.0, ttitle2.frame.origin.y+ttitle2.frame.size.height-9.0, 210, 40)] autorelease];
        ttitle3.textColor= [UIColor darkGrayColor];
        ttitle3.backgroundColor=[UIColor clearColor];
        ttitle3.numberOfLines=1;
        ttitle3.tag=71;
        ttitle3.textAlignment = NSTextAlignmentLeft;
        ttitle3.lineBreakMode=NSLineBreakByWordWrapping;
        ttitle3.font=[UIFont fontWithName:@"Arial" size:11.0];
        [cell.contentView addSubview:ttitle3];

    }

    imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[data objectAtIndex:indexPath.row] valueForKey:@"thumbnail"]]]];

    [ttitle setText:[[data objectAtIndex:indexPath.row] valueForKey:@"name"]];
    [ttitle2 setText:[[data objectAtIndex:indexPath.row] valueForKey:@"content"]];

    NSString* first=[[[data objectAtIndex:indexPath.row] valueForKey:@"hashtag"] stringByAppendingString:@"     "];
    NSString* second =[first stringByAppendingString:[[data objectAtIndex:indexPath.row] valueForKey:@"place"]];
    NSString* third=[second stringByAppendingString:@"        "];
    NSString* fourth=[third stringByAppendingString:@"¤ "];
    NSString* conversion=[[[data objectAtIndex:indexPath.row] valueForKey:@"counter"] stringValue];
    NSString* fifth=[fourth stringByAppendingString:conversion];
    [ttitle3 setText:fifth];


}
else {
    imageView =[cell viewWithTag:1];
    ttitle=[cell viewWithTag:69];
    ttitle2=[cell viewWithTag:70];
    ttitle3=[cell viewWithTag:71];
}

//STUFFOUTSIDE

// Customize cell:
// *** This section should customize the cell depending on what row or section
//  is passed in indexPath, since this is executed every time this delegate method
//  is called.



return cell;

}

2 个答案:

答案 0 :(得分:2)

问题是当重新使用单元格时,您的局部变量没有被初始化。这是imageView的当前流程:

UIImageView* imageView;

if (cell == nil)
{
    // Create imageView
    imageView=...
}

// If cell is being reused (ie cell is not nil) then imageView is nil at this point.
imageView.image=...

当您重复使用表格视图时,tableView:dequeueReusableCellWithIdentifier:会返回实际的单元格而不是nil,并且会跳过imageView的初始化。

您需要“找到”重用单元格中的imageView才能对其进行更改。

因此,我建议你修改你的逻辑:

UIImageView* imageView;

if (cell == nil)
{
    // Create imageView
    imageView=...
}
else
{
    imageView = // get a reference to the imageView
}

imageView.image=...

现在,当然,问题是“如何?”。

一种非常常见的方法是在创建视图时设置视图的tag,以便以后轻松检索它。你会像这样使用这种技术:

// Use a unique tag number for each subview.
#define MY_IMAGEVIEW_TAG 1000

UIImageView* imageView;

if (cell == nil)
{
    // Create imageView
    imageView=... // Same as before
    imageView.tag = MY_IMAGEVIEW_TAG; 
}
else
{
    // This is a cell that is being re-used and was previously created.
    // Retrieve a reference to the existing image view that is already in the cell
    imageView = [cell viewWithTag:MY_IMAGEVIEW_TAG];
}

// Now imageView is "safe" to use whether it is a new cell or one that is reused!
imageView.image=...

注意:如果您正在做很多这样的事情,那么创建一个具有每个子视图属性的UITableViewCell子类将不再需要使用标签和viewWithTag,以及让你的代码更容易阅读。

答案 1 :(得分:1)

@Inafziger已经发布了这个问题的正确答案,我只是想详细解释为什么你会看到这种“怪异”的崩溃。
不过,我不建议过度使用标签。创建UITableViewCell的子类可能是个更好的主意。

您尚未初始化imageViewttitle变量:

UIImageView *imageView; // imageView can point to anything now!
UILabel* ttitle;

通常,当你声明它们以避免这种悬空指针时,你会将局部变量初始化为nil0(无论什么都有意义)。

因为您正在重复使用表格视图,所以单元格cell并不总是nil,并且您的if子句不会被执行:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) { // Won't be executed if the cell could be dequeued!
    ...
    imageView = ...;
}

因此,如果cell可以出列,那么当您使用imageViewttitle变量时,它们仍未分配给任何内容!

然后,您将设置视图的属性:

imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[data objectAtIndex:indexPath.row] valueForKey:@"thumbnail"]]]];
[ttitle setText:[[data objectAtIndex:indexPath.row] valueForKey:@"name"]];
[ttitle2 setText:[[data objectAtIndex:indexPath.row] valueForKey:@"content"]]

imageView.image = ...;与调用[imageView setImage:...];相同。您可以在此处详细了解:http://www.cocoacast.com/cocoacast/?q=node/103

当所有人聚集在一起时:imageView未初始化,而您正在调用-setImage:。砰的一声,崩溃!

在您的情况下,imageView指向NSIndexPath课程。不过,这可能是任何事情 因此,您有效地在-setImage:类上调用NSIndexPath(相当于:+[NSIndexPath setImage:]),并且应用程序因+[NSIndexPath setImage:]: unrecognized selector sent to class 0x3c361e68错误消息而崩溃。