开发者

How to remove a subview which is a UILabel

I have a scroll view, in which I am adding multiple UIImageview's.

For each image view I am adding a UIButton and a UILabel.

Now i want to remove UILabel view.

Please find with my code below

 - (void)viewDidLoad {
    [super viewDidLoad];

    int h;
    for (h=0; h<3; h++) {
    UIImageView *k=[[UIImageView alloc]initWithFrame:CGRectMake(h*40, 0, 60, 90)];
    k.backgroundColor=[UIColor yellowColor];
    k.tag=h;

    UIButton *j=[[UIButton alloc]initWithFrame:CGRectMake(20, 20, 20, 20)];
    [j addTarget:self action:@selector(ge:) forControlEvents: UIControlEventTouchUpInside];
    j.backgroundColor=[UIColor redColor];
    [k addSubview:j];
    k.userInteractionEnabled=开发者_开发百科YES;
    [self.view addSubview:k];

    }

}

Here I am just adding an image view and a button. If label exists remove UILabel else add UILabel

Once user click on the button

-(IBAction)ge:(id)sender{


    UIImageView *imageView = (UIImageView *)[sender superview];
    for (UIView *jkl in [[sender superview]subviews]) {
        if ([jkl isKindOfClass:[UILabel class]]){ 
            [jkl removeFromSuperview];


        } else {
            UILabel *y=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 20, 20)];

            y.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Close.jpeg"]];
            [imageView addSubview:y];
        }

    }

}

but UILabel is not getting removed. Can you please help.


It looks like you're adding the label as a subview of your imageView, but the code that's trying to remove the label is looping through [[sender superview] subviews] – which are the subviews of the imageView's parent view. Try changing that code to loop through [sender subviews] instead.


You are also leaking those UIImageView and UIButton objects. You alloc/init them which sets the retain count to 1, then add them as a subview which sets retain count to 2. When the parent view containing them is released, it releases those views down to a retain count of 1, but never deletes them. You should either do an alloc/init/autorelease on them when you first create them, or release them after you add them as subviews to solve this problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜