2011-05-12 22 views
0

我需要在表格單元格中繪製圖像。到目前爲止,在創建視圖並將其分配給單元格後,我一直無法獲得對UIImageView的適當引用。例如,相同的程序對UILabel有效。嘗試通過viewWithTag獲取UIImageView引用後崩潰

我搞不​​清楚我做錯了什麼。

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

    UIImageView *imageView; 
    UILabel *title; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
             reuseIdentifier:CellIdentifier] autorelease]; 

     // Setup title 
     title = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)] autorelease]; 
     title.tag = 1; 
     [cell.contentView addSubview:title]; 

     // Setup image 
     UIImageView* imageView = [[[ UIImageView alloc] initWithFrame: 
            CGRectMake(50, 0, 50, 50)] autorelease]; 
     imageView.tag = 2; 
     [cell.contentView addSubview:imageView]; 

    } else { 
     // Get references to cell views 
     title = (UILabel *)[cell.contentView viewWithTag:1]; 
     imageView = (UIImageView *)[cell.contentView viewWithTag:2]; 
    } 

    NSLog(@"%@", [title class]);  // UILabel 
    NSLog(@"%@", [imageView class]); // CRASH! EXC_BAD_ACCESS 

    return cell; 
} 

回答

2

問題是imageView變量的範圍。如果單元格不存在,則創建一個僅存在於if塊中的新的UIImageView。它隱藏了你之前聲明的變量,並在if塊結束後消失。 而不是

UIImageView *imageView = ... 

,你只要簡單地寫

imageView = ... 

否則你創建具有無關,與你在方法的頂部聲明的對象和原始imageView是一個新的對象仍未定義。

+0

非常感謝! Objective-C的範圍和內部工作仍然有點模糊。 – Julian 2011-05-12 19:40:37

相關問題