Reputation: 763
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
Upvotes: 3
Views: 1862
Reputation: 344
You can set a tag to this view and can get "viewWithTag:" if it is returning view that means it is already added
Upvotes: 0
Reputation: 21805
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()
Upvotes: 2
Reputation: 932
Try checking that toastView
has superview or not. If not , then add it. Following if
condition executes when toastView
has not added on any view.
if ! toastView.superview
Upvotes: 0