wagashi
wagashi

Reputation: 894

ios How to remove a certain UIView that is custom made

I have a custom UIView with alpha 0.5. I want to remove the first view when another view of same type appear, so how do I do it?

So far I have written this, I get log of "not visible" all the time:

MyCustomView *myTranslation = [[MyCustomView alloc]initWithFrame:CGRectMake(0, 330, 320, 150)];

if (myTranslation.tag == 2)
{
    NSLog (@"is shown yes");
    [[myTranslation viewWithTag:2] removeFromSuperview];

}   

else
{
    NSLog(@"not visible");
    myTranslation.tag = 2;

}       

myTranslation.backgroundColor = [UIColor brownColor];

myTranslation.alpha = 0.5;

myTranslation.opaque = 0.5;

[self.view addSubview:myTranslation];
[myTranslation show];
[myTranslation release];

Upvotes: 2

Views: 542

Answers (1)

Till
Till

Reputation: 27597

You are not getting what you expect because you are instantiating a new view in any case. That new view will not be tagged at all (tag property will be set to zero), hence you get that result.

What you actually want to do is try to get the view instance from the existing viewController's view using viewWithTag as shown below. Then you check if you actually got a matching view. Only if you did not get a valid view (myTranslation equals nil), you should instantiate a new one and tag it appropriately.

MyCustomView *myTranslation = (MyCustomView *)[self.view viewWithTag:2];
if (myTranslation != nil)
{
    NSLog (@"is shown yes");
    [myTranslation removeFromSuperview];
}   
else
{
    myTranslation = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 330, 320, 150)];
    NSLog(@"not visible");
    myTranslation.tag = 2;
}

...

Upvotes: 3

Related Questions