Isha Balla Isha Balla - 6 months ago 17
Swift Question

How to check whether a view already exists in my Application Window?

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

})

}

}


This is my block of code. However, it never enters the if block. The thing I want to achieve is to not add the view continuously if it already exists there. If the view already exists in the application window,I want it to do nothing. However, it is adding the view everytime the action is being called. I have tried mostly every solution proposed like isdescendantOf(),subviews.contains().. But none has worked so far

Answer

Change your code to the following

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

Now call your notification from anywhere like

CustomNotification.sharedInstance.showNotificationWithTitleWarning()