双击时删除旧按钮

时间:2010-08-04 15:58:34

标签: iphone

UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setImage:[UIImage imageNamed:@"restaurant.png"] forState:UIControlStateNormal];
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn2 setImage:[UIImage imageNamed:@"restaurant1.png"] forState:UIControlStateNormal];

if([scaleStr isEqualToString:@"0.139738"]){

    btn1.frame = CGRectMake(330,145,5,5);       
    [imageScrollView addSubview:btn1];


} else if ([scaleStr isEqualToString:@"0.209607"]) {    
    [btn1 removeFromSuperView]; 
    btn2.frame = CGRectMake(495,217.5,10,10);
    [imageScrollView addSubview:btn2];      

}

我在UIScrollview中双击背景图片时设置了按钮。如果我再次点按两次,第一个按钮也会显示。我需要删除我先创建的按钮。

我也会在下一个条件下删除btn1。

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

这里有一些上下文可能会有所帮助,但我的猜测是你真的只是每次都创建一个新按钮,而不是引用旧按钮。因此,当您在第二次点击时调用removeFromSuperView时,您将删除一个尚未添加到视图中的按钮,而不是您在上次传递时添加的按钮。尝试使用按钮实例变量而不是本地变量。在极其松散的伪代码中:


@interface MyClass : UIView {
    UIButton *btn1;
    UIButton *btn2;
}

@implementation MyClass {
    -(MyClass *) init {
        self = [super init];

        [self setupButtons];

        return self;
    }

    -(void) setupButtons {
        btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn1 setImage:[UIImage imageNamed:@"restaurant.png"] forState:UIControlStateNormal];
        btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn2 setImage:[UIImage imageNamed:@"restaurant1.png"] forState:UIControlStateNormal];
    }

    -(void) myFunction {        
        [btn1 removeFromSuperView];
        [btn2 removeFromSuperView];     

        if([scaleStr isEqualToString:@"0.139738"]){
            btn1.frame = CGRectMake(330,145,5,5);       
            [imageScrollView addSubview:btn1];
        } else if ([scaleStr isEqualToString:@"0.209607"]) { 
            btn2.frame = CGRectMake(495,217.5,10,10);
            [imageScrollView addSubview:btn2];
        }
    }
}