OGeek|极客世界-中国程序员成长平台

标题: ios如何删除某个定制的UIView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:43
标题: ios如何删除某个定制的UIView

我有一个 alpha 0.5 的自定义 UIView。当出现另一个相同类型的 View 时,我想删除第一个 View ,我该怎么做?

到目前为止,我已经写了这个,我一直得到“不可见”的日志:

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];



Best Answer-推荐答案


您没有得到您期望的结果,因为无论如何您都在实例化一个新 View 。该新 View 根本不会被标记(标记属性将设置为零),因此您会得到该结果。

您真正想要做的是尝试使用 viewWithTag 从现有 viewController 的 View 中获取 View 实例,如下所示。然后你检查你是否真的得到了一个匹配的 View 。只有当您没有获得有效 View (myTranslation 等于 nil)时,您才应该实例化一个新 View 并适本地标记它。

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

...

关于ios如何删除某个定制的UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366824/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4