具有imageview和按钮的单元格被重用

时间:2013-03-19 06:44:46

标签: ios uitableview

我有一个包含许多单元格的表视图。在第一个单元格中,我放置了一个UIImageView来保存图片,然后在它旁边打开一个popOver按钮。 我的问题是:为什么这个单元格在检查时会被重用(cell == nil),而其他单元格正常工作。

代码如下。

P.S。这不是以编程方式使用storyboard和xib。

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

    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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


    if (indexPath.section == 0)
    {


        if(indexPath.row==0)
        {

            if(self.imageView==nil)

           {            
           self.imageView  = [[UIImageView alloc] initWithFrame:CGRectMake(30, 2, 50, 40)];

            self.imageView.image = [UIImage imageNamed:@"user.png"];

            self.imageView.backgroundColor=[UIColor blackColor];

           }

            [cell.contentView addSubview:self.imageView];


             if(self.chooseImage==nil)
            {

            self.chooseImage = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 80, 30)];

            [self.chooseImage addTarget:self action:@selector(chooseImage:) forControlEvents:UIControlEventTouchUpInside];

            self.chooseImage.backgroundColor = [UIColor blackColor];

            [self.chooseImage setTitle:@"CHOOSE" forState:UIControlStateNormal];
            }

            [cell.contentView addSubview:self.chooseImage];

        }

1 个答案:

答案 0 :(得分:0)

首先在代码末尾添加方法return cell;并使用以下代码。

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

    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

           {            
           self.imageView  = [[UIImageView alloc] initWithFrame:CGRectMake(30, 2, 50, 40)];

            self.imageView.image = [UIImage imageNamed:@"user.png"];

            self.imageView.backgroundColor=[UIColor blackColor];

           }
            [cell.contentView addSubview:self.imageView];
           if(self.chooseImage==nil)
            {

            self.chooseImage = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 80, 30)];

            [self.chooseImage addTarget:self action:@selector(chooseImage:) forControlEvents:UIControlEventTouchUpInside];

            self.chooseImage.backgroundColor = [UIColor blackColor];

            [self.chooseImage setTitle:@"CHOOSE" forState:UIControlStateNormal];
            }

            [cell.contentView addSubview:self.chooseImage];

    }


   return cell; // this line is not in your code so add this line.

}
相关问题