2016-05-16 19 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:」如果它正在返回視圖,這意味着它已被添加

相關問題