2016-05-16 75 views
2
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()..但没有工作到目前为止如何检查我的应用程序窗口中是否已存在视图?

+0

尝试使它成为一个实例函数,并使吐司成为一个实例var,并删除i t再从子视图再加入子视图然后 – Shubhank

+0

请问你可以发布一些源代码来做到这一点吗? –

+0

你能说出这个函数在哪个类中吗? – Shubhank

回答

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() 
+0

=无法正常工作。并且现在视图根本不显示 –

+0

哪一行=? '如果让prevToastView ='或'toastView =' – Shubhank

+0

谢谢你..纠正我所有的愚蠢错误后,它终于工作:) –

0

尝试检查,toastView有superview或没有。如果不是,则添加它。以下if条件在toastView尚未添加到任何视图时执行。

if ! toastView.superview 
+0

检查是否可以使用此代码在swift中检查toastView是否具有superview –

0

打电话给你通知您可以将标签设置为这一观点,并能得到“viewWithTag:”如果它正在返回视图,这意味着它已被添加

相关问题