删除UIButton的子视图

时间:2011-11-04 06:44:50

标签: iphone objective-c ios uibutton

当用户按下按钮时,我一遍又一遍地运行相同的代码。如果用户按下按钮,图像会显示在按钮上方,如果再次按下该图像,则图像将从按钮子视图中删除。

这是我的代码:

 UIImageView *overlay = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"OverlayImage.png"]];

    NSString *senderstag = [NSString stringWithFormat:@"%i", buttonFromSender.tag];
    if([[dictonaryOfImagesToDelete allKeys] containsObject:senderstag]){
        [[buttonFromSender subviews]makeObjectsPerformSelector:@selector(removeFromSuperview)]; 
    }
    else{
    [buttonFromSender addSubview:overlay];
    }
    NSString *imageName = [[NSString alloc]init];
    imageName = [arrayWithImageNames objectAtIndex:buttonFromSender.tag];

    [imagesToDelete addObject:imageName];

    [dictonaryOfImagesToDelete setObject:imagesToDelete forKey:[NSString stringWithFormat:@"%i", buttonFromSender.tag]];

我使用字典来跟踪按下了哪些按钮。而不是删除按钮上的imageview,它删除整个按钮。我怎样才能删除imageview而不是按钮呢?

谢谢:D

2 个答案:

答案 0 :(得分:0)

如果要为按钮状态显示不同的图像,可以直接初始化按钮,以便在该状态下加载图片。 例如,启用/禁用,或选择/取消选择(正常)

UIButton* myButton = [UIButton buttonWithType:UIButtonTypeCustom];    
[myButton setImage:[UIImage imageNamed:@"My Image"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"My Other Image"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"BG Img"] forState:UIControlStateNormal];

参考文献:

背景图片: http://developer.apple.com/library/IOS/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instm/UIButton/backgroundImageForState

按钮图片: http://developer.apple.com/library/IOS/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instm/UIButton/setImage:forState

答案 1 :(得分:0)

我最终制作了叠加层的UIImageview,一个UIButton。这允许为它设置动作。以下是使用的代码:

        UIImage *image = [UIImage imageNamed:@"OverlayImage.png"];
    UIButton *overlay = [[UIButton alloc]init];
    overlay.frame = CGRectMake(0, 0, 100, 150);
    [overlay setImage:image forState:UIControlStateNormal];
    [overlay addTarget:self action:@selector(removeSelectedImage:) forControlEvents:UIControlEventTouchUpInside];
    overlay.tag = buttonFromSender.tag;


    [buttonFromSender addSubview:overlay];

    NSString *imageName = [[NSString alloc]init];
    imageName = [arrayWithImageNames objectAtIndex:buttonFromSender.tag];

    [imagesToDelete addObject:imageName];

    [dictonaryOfImagesToDelete setObject:imageName forKey:[NSString stringWithFormat:@"%i", buttonFromSender.tag]];

这设置了新的UIButton

然后摆脱UIButton我做了这个:

-(IBAction)removeSelectedImage:(id)sender{
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
NSString *tag = [NSString stringWithFormat:@"%i", button.tag];
NSString *deleteWhat = [[NSString alloc]init];
deleteWhat = [dictonaryOfImagesToDelete objectForKey:tag];
[imagesToDelete removeObject:deleteWhat];
[dictonaryOfImagesToDelete removeObjectForKey:tag];
}