无法在for循环中删除动态创建的UIButton

时间:2015-03-19 15:53:49

标签: ios objective-c

我正在开发一个应用程序,其中列出了联系人电话号码,具体取决于为联系人存储的电话号码的数量。我需要一个与每个电话号码对应的按钮。我用if条件写了一个for循环

现在当用户点击一个有3个号码的联系人时,按钮显示完美,然后他按下后退按钮并转到一个带有1个号码的联系人,仍显示所有三个按钮。 我试过[btn autorelease]; [btn setEnabled:NO]; [btn removeFromSuperView]; 但问题仍未解决。下面是代码剪辑:

    for (int i=0;i<ABMultiValueGetCount(lMap);i++)   {
        if (i==0)   {
     //       UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

            btn.frame = CGRectMake(230,110,88,35); //The position and size of the button (x,y,width,height)
            [btn setTitle:@"SMS" forState:UIControlStateNormal];
            [btn addTarget:self
                    action:@selector(showAbout)
          forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
            [self.view addSubview:btn];
            [btn autorelease];

        }
        else if (i==1)  {
       //     UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(230,150,88,35); //The position and size of the button (x,y,width,height)
            [btn setTitle:@"SMS" forState:UIControlStateNormal];
            [btn addTarget:self
                    action:@selector(showAbout)
          forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
            [self.view addSubview:btn];
                            [btn autorelease];
        }
        else if (i==2)  {
      //      UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(230,190,88,35); //The position and size of the button (x,y,width,height)
            [btn setTitle:@"SMS" forState:UIControlStateNormal];
            [btn addTarget:self
                    action:@selector(showAbout)
          forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
            [self.view addSubview:btn];
             [btn autorelease];
        }

1 个答案:

答案 0 :(得分:0)

这应该有用。

// Declare a constant
int buttonTagConstant = 200;

// Before creating the buttons, delete the old ones first.
for (UIView* subV in self.view.subviews)
{
    if ([subV isKindOfClass:[UIButton class]] && subV.tag == buttonTagConstant) 
    {
        [subV removeFromSuperview];
    }
}

int y_of_the_button = 110;

// Also I refactored your code as below
for (int i=0;i<ABMultiValueGetCount(lMap);i++)
{
    btn.frame = CGRectMake(230, y_of_the_button, 88, 35); //The position and size of the button (x,y,width,height)
    [btn setTitle:@"SMS" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(showAbout) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
    btn.tag = buttonTagConstant;
    [self.view addSubview:btn];
    y_of_the_button += 40;
}