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

时间:2016-05-16 09:31:15

标签: ios swift uiview

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块。我想要实现的是,如果视图已经存在,则不要连续添加视图。如果视图已存在于应用程序窗口中,我希望它不执行任何操作。但是,每次调用操作时都会添加视图。我已经尝试了大多数提出的每个解决方案,如isdescendantOf(),subviews.contains()..但到目前为止还没有工作

3 个答案:

答案 0 :(得分:2)

将您的代码更改为以下

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

现在可以从任何地方拨打您的通知

CustomNotification.sharedInstance.showNotificationWithTitleWarning()

答案 1 :(得分:0)

尝试检查toastView是否有超级视图。如果没有,那么添加它。如果在任何视图上未添加if,则会执行toastView条件。

if  ! toastView.superview

答案 2 :(得分:0)

您可以为此视图设置标记,并且可以获取" viewWithTag:"如果它返回视图意味着它已被添加