2011-04-13 59 views
1

我在编码时遇到了一个问题,也就是说,我使用带自定义按钮的循环在视图中显示了20幅图像。一段时间后,我正在用新图像更改按钮图像。但是在这里发生的旧图像显示在当前图像的背面。如何删除旧图像的新图像在objective-c

for(currentRow = 0; currentRow < 5; currentRow++) 
    { 
     for (currentColumn = 0 ; currentColumn < 4; currentColumn++) 
     { 
      if(indexValue<20) 
      { 
       printf("\n index value %d",indexValue); 
       A *aObject = [aList objectAtIndex:indexValue]; 

       MyCustomButton *myButton = [[MyCustomButton alloc] initWithIdValue:aObject.aName]; 
       CGRect imageFrame = CGRectMake(currentColumn * 80+5, currentRow * 80+5, 67, 67); 
       [myButton setImage:[UIImage imageNamed:aObject.aName] forState:UIControlStateNormal]; 
       [myButton setFrame:imageFrame]; 
       myButton.backgroundColor=[UIColor clearColor]; 
       [myButton addTarget:self action:@selector(aAction:) forControlEvents:UIControlEventTouchUpInside]; 
       [myView addSubview:myButton]; 
       [myButton release]; 
       myButton = nil; 
} 
} 
} 

帮我出这一点,

谢谢 马丹·莫汉。

+1

如果你粘贴你的代码,我相信我们会在没有时间修复 – 2011-04-13 13:31:09

+0

请发布一些代码,它很难分辨没有它的情况。话虽如此,这听起来像你正在分配新的UIImageViews,而不是改变旧的图像。 – MCannon 2011-04-13 13:31:27

+0

编辑该问题并添加循环,在其中最初更新UIButton图像。 – 2011-04-13 13:31:36

回答

1

正如onnoweb已经提到: 你不应该在每次你想改变图像时添加一个新的按钮。 我会选择的方法是,在视图的viewDidLoad中创建所需的所有按钮并将它们添加到那里。 例如像这样:(伪代码)

- (void)viewDidLoad 
{ 
    for(int i = 0; i < columnCount; i++) 
    { 
     for(int j = 0; j < rowCount; j++) 
     { 

      MyCustomButton *myButton = [[MyCustomButton alloc] initWithIdValue:aObject.aName]; 
      CGRect imageFrame = CGRectMake(currentColumn * 80+5, currentRow * 80+5, 67, 67); 
      forState:UIControlStateNormal]; 
      [myButton setFrame:imageFrame]; 
      myButton.backgroundColor=[UIColor clearColor]; 
      [myButton addTarget:self action:@selector(aAction:) forControlEvents:UIControlEventTouchUpInside]; 
      [myView addSubview:myButton]; 
      [myButton release]; 
      myButton = nil; 
     } 
    } 
} 

然后,你可以更改与以下行循环的图像:(伪代码)

  myButton = buttonMatrix[row][column]; 
      [myButton setImage:[UIImage imageNamed:aObject.aName] forState:UIControlStateNormal]; 

这也是要少得多内存占用比始终创建新按钮而不释放旧的按钮。

+0

@Madan Mohan 我在这里写的代码不适合您复制并粘贴到您的项目中。那么它不会工作。我只是使用您发布的代码以伪代码的形式编写此代码,以便您考虑自己编写的代码。这样你就不会再犯这个错误了。 :) – Maverick1st 2011-04-13 16:27:15

0

有两个选项来解决此问题:

1)保存您的循环创建的按钮指针,更新图像时,使用该按钮指针调用setImage:forState:再次,这将取代在新图像的按钮中的旧图像。并保存按钮的init/destroy时间。

2)将按钮指针保存为步骤1),调用[button removeFromSuperView]从超级视图中删除按钮,然后重新创建一个新按钮并再次插入超级视图。这是不推荐的方法,因为旧按钮将被销毁,并且新按钮将被初始化,这两个操作都会降低性能(时间),并且如果在按钮顶部添加了其他子视图,则在创建新按钮后,您需要将按钮顶部的所有视图重新放在顶部。所以如果您没有任何特定的原因需要重新创建一个新按钮,请按照步骤1),它非常简单快捷。