I have implemented action sheet though alert controller. I want to display a button like cancel button with "Pay" Text written on it.
Issue is makeCall() function call when pay button is clicked , And when rest of the screen is tapped makeCall() function is called again.
How can I identify that action is called through pay button action or through Tapp on rest of the screen? I only want to make call to makeCall() function when pay button is tapped.
alertController = UIAlertController(title: "", message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Pay", style: .cancel) { (UIAlertAction) in
printLog("cancelAction")
makeCall()
}
cancelAction.isEnabled = false
alertController.addAction(cancelAction)
self.present(alertController, animated: true) {}
Here, alert controller view userInteraction disable so when tap outside alert controller not close.
You can do like this:
self.present(alertController, animated: true){
if let mainView = alertController.view.superview?.subviews[0]{
mainView.isUserInteractionEnabled = false
}
}
OR
self.present(alertController, animated: true) {
if let allContainerView = alertController.view.superview?.subviews{
for myview in allContainerView{
if (myview.gestureRecognizers != nil){
myview.isUserInteractionEnabled = false
}
}
}
}
I hope it will work for you.
I don't find any solution that how can you identify that action is called through pay button action or through Tap on rest of the screen.
but the alter solution is that you add tap gesture on rest view. So, you can identify that if cancel button tap or tap in rest of the screen.
alertController = UIAlertController(title: "", message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Pay", style: .cancel) { (UIAlertAction) in
printLog("cancelAction")
makeCall()
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
alertController.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}
#objc func dismissAlertController(){
self.dismiss(animated: true, completion: nil)
print("through Tap on rest of the screen")
}
Related
On certain conditions, if users intent to leave the current view (e.g. pop the current view, push other view, or select other tab items etc.), a UIAlertController should be presented to confirm users' real intention.
Users can press OK to proceed the view transitioning, or Cancel to stay on the current view.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if someConditions {
promptUIAlert()
}
}
Any solutions that can achieve that requirements?
First of all, you cannot handle this is viewWillDisappear because at this point it has already been decided that the view will disappear. You need to handle this wherever you have view transitions (push, pop, present, dismiss).
You have to handle the transitions in the confirmation alert action. You alert would look something like this.
let alert = UIAlertController(title: "Wait!", message: "Are you sure you want to leave this view?", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default) { (alertAction) in
//Handle view transitioning here
}
let cancel = UIAlertAction(title: "Cancel", style: .destructive) { (alertAction) in
//Do nothing?
}
alert.addAction(ok)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
You can't intercept and retain the user in the same ViewController once the viewWillDissaper is fired. You should do it in advance. My suggestion is to add a UIBarButton with a label Back to the navigationItem.leftBarButtonItem and manually check whether the user wants to navigate or not. This is the closest you can get.
also, you can use the UIAlertViewController to confirm whether the user wants to navigate or not.
//inside viewDidLoad
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(handleBack))
//define another function to handle the selctor
#objc func handleCancel(){
if someConditions {
promptUIAlert()
}
}
//you function should be like this with UIAlertController
func promptUIAlert(){
let alertController = UIAlertController(title: "Error", message: "Some message", preferredStyle: .alert)
let CancelAction = UIAlertAction(title: "Cancel", style: .default) { (action) in
//type your custom code here for cancel action
}
let OkAction = UIAlertAction(title: "OK", style: .default) { (action) in
//type your custom code here for OK action
}
alertController.addAction(OKAction)
alertController.addAction(CancelAction)
self.present(alertController, animated: true)
}
Doing something inside viewWillDissaper would be handy to save some unsaved data behind the screen. But not to prompt and ask the user whether they want to remain in the same ViewController.
I have a UIAlertController with a style of ActionSheet.
I've added a cancel action to it.
The thing is that for some reason when the user taps outside of the ActionSheet box - the alert is dismissed.
How can I disable this behavior? I want the user to press the cancel button directly.
swift 4 / Xcode 11
Hi. To disable user interaction (example: tapping anywhere but the cancel button), call the present method in your alert function and set it's completion closure as below code.
present(alertController, animated: true) {
alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
}
The whole example:
func alertMe() {
let alertController = UIAlertController(title: "Tapping Test", message: "User Interaction on the view is disabled", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel) { UIAlertAction in
// do something/call someone/or nothing :)
NSLog("cancel Button is Pressed")
}
alertController.addAction(cancelAction)
present(alertController, animated: true){
alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
}
}
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.
I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if changesMade {
let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)
let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
self.saveSession()
})
alertController.addAction(saveOption)
alertController.addAction(cancelOption)
present(alertController, animated: true)
}
}
Actually, there is a very simple solution: navigationItem.hidesBackButton = true - this will hide "BACK" button and disable swipe-to-back feature. 🤓
There are two cases here:
User can pop using back button.
User can pop using interactive pop gesture of navigation controller.
I think you should use a custom back button and name it Done and write your logic of showing alert on press of this button.
Using the custom back button would disable the interactive pop gesture by default and you will be spared from playing the dance of enabling/disabling interactivePopGesture on navigation controller.
block pop action till your changes are not saved like this
if changesMade {
let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)
let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
self.saveSession()
self.navigationController?.popViewController(animated: true)
})
alertController.addAction(saveOption)
alertController.addAction(cancelOption)
present(alertController, animated: true)
}
Update - Add this below custom button and its action in child View controller which is being pushed from parent View Controller
so, without satisfying your condition user can not move from child to parent again
For customising action of navigation backButton you need to manually add a back Button using below line , you can Customise barButton being added here in DidLoad
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backToInitial(sender:)))
It will perform required Action
#objc func backToInitial(sender: AnyObject) {
if changesMade {
let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)
let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
self.saveSession()
self.navigationController?.popViewController(animated: true)
})
alertController.addAction(saveOption)
alertController.addAction(cancelOption)
present(alertController, animated: true)
}
}
and I do not think you can stop default back button action task of navigation Controller as it is designed the way to perform it
But yes you can manage it in ViewWillDisappear as :
override func viewWillDisappear(_ animated: Bool) {
if self.isMovingFromParentViewController || self.isBeingDismissed {
self.navigationController?.popViewController(animated: false) //here task but will not result as Expected output
}
}
-----------------Re-Update ---------------
in swift I used a objective-C class to get output as expected now, childViewController pop action is being controller from a alert using default back button that we get from navigation controller
You can customise you pop action to perform or not until your condition is not satisfied
Github Link - https://github.com/RockinGarg/NavigationBackButton.git
I found a much more elegant solution (in my opinion).
It works no matter how the user triggers the pop (accessibility escape, swipe back gesture, tapping back) since it overrides the built in pop methods that the system uses.
Swift 5
public class DiscardSafeNavigationController:UINavigationController {
/// Should the pop be prevented? Set this to `true` when you have changes which need to be protected
public var hasUnsavedChanges:Bool = false
/// Show a prompt on the top most screen asking the user if they wish to proceed with the pop
/// - Parameter discardCallback: The callback to use if the user opts to discard
private func confirmDiscardChanges(discardCallback:#escaping (()->())) {
let alertController = UIAlertController.init(title: "Discard changes", message: "Are you sure you want to discard any unsaved changes?", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction.init(title: "Discard", style: UIAlertAction.Style.destructive, handler: { (_) in
discardCallback()
//User elected to discard and so, at this point, they no longer have changes to save
self.hasUnsavedChanges = false
}))
alertController.addAction(UIAlertAction.init(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
self.topViewController?.present(alertController, animated: true, completion: nil)
}
override func popViewController(animated: Bool) -> UIViewController? {
//If there aren't unsaved changes, popping is safe
if !hasUnsavedChanges {
return super.popViewController(animated: animated)
}else {
//Changes have been made. Block the pop and first check with the user before continuing
confirmDiscardChanges {
super.popViewController(animated: animated)
}
return nil
}
}
}
and when you want to enable discard protection from any child view controllers, simply use:
(self.navigationController as? DiscardSafeNavigationController)?.hasUnsavedChanges = true
and then any time the navigation controller is asked to pop it, the navigation controller will ask the user first.
I have an app with a popover. As I'm coming out of the popover. I am dismissing the popover via a UIAlertController (user answers Yes). Before dismissing the popover, though, I am calling a function on the delegate. Within that function is another UIAlertController. The second UIAlertController is not displaying because of the following error:
Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior.
To demo this here, I created a quick project that shows the problem. It is just a view controller with a button that calls the popover and a button on the popover that closes it and calls a delegate function containing another UIAlertController.
This is the code for the view controller that calls the popover:
//Delegate function called from popover
func doSomeStuff() {
let alert = UIAlertController(title: "Some Stuff", message: "Do you want to do some stuff", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {action in
print("We did something here.")
}))
alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
#IBAction func callPopover(sender: UIButton) {
let popoverVC = self.storyboard?.instantiateViewControllerWithIdentifier("PopoverView") as! PopoverController
popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
popoverVC.preferredContentSize = CGSizeMake(200, 200)
if let popoverController = popoverVC.popoverPresentationController {
popoverController.backgroundColor = UIColor.lightGrayColor()
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
popoverController.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)
popoverController.sourceView = callPopoverButton
popoverController.delegate = self
popoverVC.delegate = self
self.presentViewController(popoverVC, animated: true, completion: nil)
}
}
//Allows popover to present on devices besides iPad.
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle{
return UIModalPresentationStyle.None
}
The callPopover function is the action for the button on the first screen.
This is the code for the popover screen:
var delegate: ViewController!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func returnToMainView(sender: UIButton) {
let alert = UIAlertController(title: "Dismiss Popover", message: "Do you want to dismiss this popover?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {action in
self.delegate.doSomeStuff()
self.dismissViewControllerAnimated(true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
When tapping the popover button on the first screen, the popover displays correctly:
Tapping the return button displays the alert:
Clicking Yes returns from the alert and should display the second alert, but that's where I get the error.
I think that the second alert is not displaying because the popover has not finished being dismissed, but have no idea how to get around it.
I see that the you are presenting the second popup view controller from the first popup view controller which is being dismissed. That is causing the issue.
Instead why can't you present the second view controller from the navigation controller instead of first popup view controller.
Change this line of presentViewController(alert, animated: true, completion: nil) to self.navigartionController.presentViewController(alert, animated: true, completion: nil) in yourdoSomeStuff() method so that the first popup can dismiss freely and the navigation controller actually presents your second popup. Hope this helps!
I want to dismiss my UIAlertViewController by tapping outside of the UIAlertViewController, on tapping on black screen space. I've tried this:
self.presentViewController(alertViewController, animated: true, completion:{
alertViewController.view.superview?.userInteractionEnabled = true
alertViewController.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:))))
})
but it just closes if I tapped on UIAlertViewController. But I want outside, where half-blacked screen tapped.
Is it possible?
UPDATE
#IBAction func shareButtonTapped(sender: UIButton) {
let alertViewController = UIAlertController(title: "Share on social networks", message: "Where do you want to share?", preferredStyle: .ActionSheet)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissAlertView:")
self.view.addGestureRecognizer(tapGestureRecognizer)
let facebookAction = UIAlertAction(title: "Facebook", style: .Default) { (alert: UIAlertAction) -> Void in
}
let twitterAction = UIAlertAction(title: "Twitter", style: .Default) { (alert: UIAlertAction) -> Void in
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Destructive) { (alert: UIAlertAction) -> Void in
}
alertViewController.addAction(facebookAction)
alertViewController.addAction(twitterAction)
alertViewController.addAction(cancelAction)
self.presentViewController(alertViewController, animated: true, completion:{
alertViewController.view.superview?.userInteractionEnabled = true
alertViewController.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:))))
})
}
AlertClose function:
func alertClose(gesture: UITapGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
If you are using ActionSheet style there is no need to do this. Because when you tap on half-blacked screen view controller automatically will be dismissed.
But if you want to use with Alert style do following (without: alertViewController.view.superview?.userInteractionEnabled = true) :
self.presentViewController(alertViewController, animated: true, completion: {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:)))
alertViewController?.view.superview?.addGestureRecognizer(tapGestureRecognizer)
})
Try to add UITapGestureRecognizer to your UIWindow class like
view.window.addGestureRecognizer()
implement UIGestureRecognizerDelegate method shouldReceiveTouch
and check your tapped view
Hope this help