Close a modal view with a button in Swift? - swift

Learning some view controller basics and am stuck on how to dismiss a modal with a button.
In my slimmed-down example, I have a two view setup with the initial view and the modal. The first view has a button that successfully pops up the modal. On the modal, there is a button that should dismiss itself.
According to other posts and documentation, I should be able to run simple code attached to the button like this:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func CloseModal(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
When I tap the "Close Modal" button nothing happens. What am I missing here? Am I putting this code in the wrong place? Currently, it's in the main ViewController.swift file.

The other approach is to use an unwind segue to your main view controller. Just add an “unwind action” in the first view controller:
class ViewController: UIViewController {
#IBAction func unwindHome(_ segue: UIStoryboardSegue) {
// this is intentionally blank
}
}
Just give this unwind action a meaningful name, unwindHome in this example, so that, if and when you have multiple unwind actions later on, you can easily differentiate between them.
Then you can control-drag from the button in the second scene to the “exit” control and select the appropriate unwind action:
This has a few nice aspects:
The “close” button no longer cares how you presented it, it will unwind however is appropriate (e.g. if you later change the initial segue to be a show/push segue, the unwind segue will still work without any code changes).
Because you’re now using a segue to unwind, the presented view controller can use its prepare(for:sender:) to send data back, should you eventually need to do that.
If you want, you can unwind multiple scenes. For example if A presents B, and B presents C, you can obviously unwind from C to B, but you can also unwind all the way from C to A if you want.
So, while dismiss works, unwind segues are another alternative.

You actually have two ViewController screens, but it looks like you have one ViewController class? And is the 2nd screen connected to a class?
Must be in the class that belongs to the second screen of the closeModal method.
//This is First ViewController, OpenModal Button is here
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
// The name of the class and the Viewcontroller in the storyboard have to be the same, and CloseModol Button and function need to be here
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func CloseModal(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
Don't forget to set the name of the ViewController in Storyboad;
from FirstViewController to SecondViewController

Related

How to unwind to home, and then segue forward in one action

I want to tap the "Go To DestinationVC" button in the SourceVC, and have it safely unwind back home, and then segue forward via a different route to the DestinationVC.
I tried just calling a performSegue in side the unwinding segue function:
#IBAction func UnwindAndSegueToDestination(_ segue: UIStoryboardSegue) {
performSegue(withIdentifier: "SegToDest", sender: nil)
}
However, this results in the DestinationVC briefly loading, and then being replace with the HomeVC.
I would recommend putting it in the viewDidAppear of the HomeVC if doing it the way you described isn't working. I would pass a Bool value during the unwind segue that tells the Home VC to triggers a segue in the viewDidAppear. Once that segue is triggered, make sure to set that Bool value to false again. Obviously the Bool value would be passed in the prepare to segue method in the source VC.

Perform UnwindSegue correctly

I am trying to create an Unwind segue that brings from the DetailViewcontroller to the SecondViewcontroller.
I have created an IBAction like this one that can be intercepted by Segues :
#IBAction func segueToSecondVC(sender: UIStoryboardSegue) {
print("segue intercepted by IBAction segueToSecondVC")
}
An placed it in the receiver ViewController (secondViewController).
Then I moved to the Detailviewcontroller and clicked to the third figure on the top of the viewcontroller (exit),clicked to the segueToSecondVC IBAction that appeared in the list of events and dragged it into the button "TURN BACK"(placed in the Detailviewcontroller) in order to associate the button to the event.
In this way the button should be connected with the event and should turn back to the secondVC with an automatic Hidden Segue.
But it doesn't work, the simulator crash and I am redirected to xCode editor with an error in the Appdelegate that says "Thread 1: signal SIGABRT"
I don't know why it doesn't work, anyone could help me?
you can use Unwind like this:
#IBAction func prepareForUnwind(segue: UIStoryboardSegue){}
#IBAction func closePressed(_ sender: Any) {
performSegue(withIdentifier: "unwindToAnotherVC", sender: nil)
}
good rule, is to add all your segues names to constants file:
Create swift file
import Foundation
// Segues
let TO_LOGIN = "toLogin"
let TO_CREATE_ACCOUNT = "toCreateAccount"
let UNWIND = "unwindToChannel"
and then use UNWIND in
#IBAction func closePressed(_ sender: Any) {
performSegue(withIdentifier: UNWIND, sender: nil)
}

Data between view controllers not passing

I am creating an application in which there are 6 view controller in storyboard. The thing is that data is shared between the default view controller and the first one ( say A and B) which i added. i am using the prepareforseque method for passing data. the problem started when i added two more view controller. lets say C and D i created two new swift files and changed the two view controller class name. i created a textbox and button in C and label in D. when i pressed the button, the value of the text field is not passing into the D view controller although i used the same methods and code which i used for A and B. do i have to do anything else when i want to pass data between two newly added view controller.
first viewcontroller in which when a button is pressed value 1 needed to be passed:
class PlaySelectMenu: UIViewController {
var value = Int()
#IBAction func twotofive(sender: AnyObject) {
value = 1
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let nextView : PlayGameView = segue.destinationViewController as! PlayGameView
nextView.x = value
}
}
the second view controller which receive the value and print it
import Foundation
import UIKit
class PlayGameView: UIViewController{
var x = Int()
override func viewDidLoad() {
super.viewDidLoad()
print(x)
}
}
here i have added both the view controller from the object library and not working with the default one which is present in storyboard by default. i dont know why these two viewcontroller are not working. please help.
Regards Dev
One solution would be to write the data out to NSUserDefaults and then read it back from NSUserDefaults in the other view controller. Probably not the proper or correct way to share data between two view controllers, but it's been a reliable work around for me.
Other than that, you'd need to share your code so that we can see what's occurring.
Can you post also the code in your controllers C & D. And also if you have copy/paste the code inside your first two controllers into the two others, are you sure that in your prepareForSegue method you have changed the name of the destination segue ?
Assuming you have created the segue in Storyboard:
All you need is to do is put all of needed updates in prepareForSegue because twotofive is called after prepareForSegue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
value = 1
let nextView : PlayGameView = segue.destinationViewController as! PlayGameView
nextView.x = value
}
Since you have connected your segue from button click to view controller, when you press button segue is automatically called. Instead of connecting segue from button to VC, connect VC to VC. Then in button click method at the last add below line:
#IBAction func twotofive(sender: AnyObject) {
value = 1
self.performSegueWithIdentifier("<Name of the segue identifier>", sender: self)
}
This will call your prepareForSegue. If you are calling more then one VC using segue from a VC then you can use segue.identifier to check which VC was called as below
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "CVC" {
}

How do you make a modal view appear outside of a controller?

I am trying to program a little game just to apply the concepts I learned in this course myself. When the game opens up, I would like for a custom modal view to tell the user how to play. Likewise, when they lose, I want to present a results page, which would be inside an if statement. I've searched all over the internet, and I can't find a way to display these views without an error. All that this video shows is how to show a display a view when a button is pressed; how do I display a custom modal view on command in code? (I am very new to Swift, so try to put it in layman's terms.) Thanks!
import UIKit
var numberValue = 0
let randomInt = getRandomNumber()
class ViewController: UIViewController {
#IBOutlet weak var buttonLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("HowToPlayView") as! HowToPlay
self.presentViewController(vc, animated: true, completion: nil)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonPressed() {
numberValue += 1
updateButtonValue(buttonLabel)
}
}
#IBAction func buttonPressed() {
numberValue += 1
updateButtonValue(buttonLabel)
}
}
That's my view controller. Getting error: Thread 1: EXC_BAD_ACCESS
My view in interface and connections
enter image description here
Ok, let's try a different approach to solve this issue. Above your ViewController you should see three different buttons like this:
Click on the first button and Ctrl + Drag to the view that you want to display and choose display modally. After that is done you should see this arrow appear:
This is called the segue from the first view to the second view and you can call this in your code to transition from one view to the next, but first we have to give our segue an identifier. You can do this by clicking on the arrow and a window should come up like this:
As you can see you will have to fill out the identifier field, and in my case I just named it "myAwesomeSegue".
Lastly, in the first ViewController run this code when you need to present the next view controller:
performSegueWithIdentifier("myAwesomeSegue", sender: nil)
Please note that if you use this method just delete the previous code you had before as this is a brand new approach (so basically delete this code):
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("HowToPlayView") as! HowToPlay
self.presentViewController(vc, animated: true, completion: nil)
Final code for the firstViewController:

segueForUnwindingToViewController in iOS 9

I have a Custom Segue exhibiting a view controller, and then have a corresponding Custom Unwind Segue. This code has worked fine in iOS 8, and is implemented by engendering subclasses of UIStoryboardSegue and implementing the perform method. Then I override the following method in my custom Navigation Controller
func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String) -> UIStoryboardSegue {
var segue: UIStoryboardSegue
if (fromViewController is MyViewController.self) {
segue = CustomSegue(identifier: identifier, source: fromViewController, destination: toViewController)
//Custom Unwind Segue
}
else {
var unwindSegue: UIStoryboardSegue = super.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)
//Normal Unwind Segue
segue = unwindSegue
}
return segue
}
In iOS 9, segueForUnwindingToViewController is deprecated. It still works for the MyViewController CustomSegue; however, the default unwind segue no longer works for any other unwind segue. Although calling the method on super returns an unwind segue, the segue never occurs, the view controller is never popped, and the user can never go back to the previous screen. So just to be clear, if I use a regular show segue, the corresponding unwind segue calls the deprecated method, which calls the method on super, and does not work.
If Controller B unwinds to controller A, then in controller A:
#IBAction func viewController-B-DidExit(segue: UIStoryboardSegue) {
let controller = segue.sourceViewController as! viewController-B
}
Then in viewContoller B connect the object you want to exit from to the exit.