Ios 如何检查我的应用程序窗口中是否已经存在视图?

Ios 如何检查我的应用程序窗口中是否已经存在视图?,ios,swift,uiview,Ios,Swift,Uiview,这是我的代码块。但是,它从不进入if块。我想要实现的是,如果视图已经存在,就不要继续添加它。如果视图已经存在于应用程序窗口中,我希望它什么也不做。但是,每次调用操作时,它都会添加视图。我已经尝试了几乎所有提出的解决方案,比如isDescendatof()、subviews.contains()。。但是到目前为止还没有一个成功尝试检查toastView是否具有superview。如果没有,则添加它。当未在任何视图上添加toastView时,执行以下if条件 class func showNotif

这是我的代码块。但是,它从不进入if块。我想要实现的是,如果视图已经存在,就不要继续添加它。如果视图已经存在于应用程序窗口中,我希望它什么也不做。但是,每次调用操作时,它都会添加视图。我已经尝试了几乎所有提出的解决方案,比如isDescendatof()、subviews.contains()。。但是到目前为止还没有一个成功

尝试检查
toastView
是否具有superview。如果没有,则添加它。当未在任何视图上添加
toastView
时,执行以下
if
条件

class func showNotificationWithTitleWarning(controller:UIViewController,title :String, subtitle :String){

        let subtitle = subtitle
        var isTrue : Bool = false


        //let horizontalPadding:CGFloat = 0.0
        let deviceWidth:CGFloat = Device.DeviceWidth
        //let deviceHeight:CGFloat = Device.DeviceHeight
        let height:CGFloat = 64.0

        let contentFrame:CGRect = CGRectMake(0,0 , deviceWidth ,height)

        var toastView:CustomTopNotification!
               toastView = CustomTopNotification(frame:contentFrame,Str_title:subtitle)

        if  toastView.superview === UIApplication.sharedApplication().delegate?.window!! {


                        toastView.removeFromSuperview()
            print("Already there")

        } else {
            UIApplication.sharedApplication().delegate?.window!!.addSubview(toastView)


            toastView.frame.origin.y = -80

            UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
                toastView.frame.origin.y =  0
                controller.view.layoutIfNeeded()

                },completion: {_ in

            })

        }

    }

将代码更改为以下内容

if  ! toastView.superview
现在从任何地方调用您的通知,如

class CustomNotification  {
   static let sharedInstance = CustomNotification()

   private var toastView: CustomTopNotification?
   func showNotificationWithTitleWarning(controller:UIViewController,title :String, subtitle :String){
            if let prevToastView = toastView {
                  prevToastView.removeFromSuperView()
            }
           //prev code of function here
           // change only one line in it
            toastView:CustomTopNotification!
               toastView = CustomTopNotification(frame:contentFrame,Str_title:subtitle)
        }
}

您可以为此视图设置一个标记,并可以获得“viewWithTag:”如果它返回的视图意味着它已被添加

请尝试将其作为实例函数,并将toast作为实例变量,在再次将其添加到子视图之前,请先将其从superview中删除,然后再将其添加到子视图中。是否可以发布一些源代码来执行此操作?是否可以确定此函数位于哪个类中?此函数位于自定义类CustomNotification中。ToastView的类型为CustomTopNotification,这是UIView类型的自定义类。如果swift=中的代码不起作用,则无法检查ToastView是否具有superview。现在视图根本不显示哪一行=<代码>如果让prevToastView=或
toastView=
谢谢。。在纠正了我所有愚蠢的错误后,它终于奏效了:)
CustomNotification.sharedInstance.showNotificationWithTitleWarning()