Isha Balla Isha Balla - 2 years ago 82
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!! {

print("Already there")

} else {

toastView.frame.origin.y = -80

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

},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 Source

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 {
           //prev code of function here
           // change only one line in it
               toastView = CustomTopNotification(frame:contentFrame,Str_title:subtitle)

Now call your notification from anywhere like

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download