无法删除循环内部动态创建的UIButton



我正在开发一个应用程序,该应用程序根据为联系人存储的电话号码列出联系人的电话号码。我需要一个对应每个电话号码的按钮。我已经写了一个如果条件的for循环

现在,当用户点击一个有3个数字的联系人时,按钮会完美显示,然后他按下后退按钮,转到一个有1个号码的联系人,仍然会显示所有三个按钮。我试过[顺便说一下自动释放];[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];
        }

这应该可以工作。

// 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;
}

最新更新