Change variable while dismissing modal controller - swift

EDIT: I have decided to change the way my app works, so this problem is solved. Thanks to everyone who helped!
I have a modal controller where when I press a button it dismisses the view. What I want to do is change a variable in another view controller when I dismiss it, is that possible? Or, if this doesn't work, is there a way for me to access the changed variable of another swift file? I will add my code below:
class PopupViewController: UIViewController {
var event = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func dismiss(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func event910(_ sender: Any) {
event = "storyTime"
dismiss(animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ViewController
vc.event = event
}
}
I want to pass the changed variable "event" to another view controller, how can I do this?

Delegate View Controller is as follows. : -
it is the place where you will send the data to the next swift file
protocol myprotocol {
func anyfunction(_ param1:String)
}
struct mystruct1 {
var delegate:myprotocol?
// where you want tot start the delegate / send the data to the next file
func anymethod(){
delegate.anyfunction(sendTheDataYouWant)
}
}
// it is here you will receive the data
class anyclass:UIViewController ,myprotocol {
let class1 = mystruct1()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
class1.delegate = self
}
func anyfunction(param1:String){
// here Save the data you want
// because this function will be triggered as delegate will be called
}
}
ps:- I reccomend you to read https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
& apple docs

Related

Value not passing between viewControllers

Struggling to get my viewControllers to send value from the main viewController to a second. I want it to happen on a button click, I'm going to get the value from the button and pass it to the new form. But it just isn't working.
Code for main ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func butClick(_ sender: UIButton) {
NSLog("Button Pressed : %#",[sender .currentTitle])
//var tt = [sender .currentTitle]
// Create the view controller
let vc = TimesTablesViewController(nibName: "TimesTablesViewController", bundle: nil)
vc.passedValue = "xx"
self.performSegue(withIdentifier: "pushSegue", sender: nil)
}
}
Code for second viewController called TimesTablesViewController:
class TimesTablesViewController: UIViewController {
#IBOutlet weak var titleLabel: UILabel!
var passedValue:String = ""
override func viewDidLoad() {
super.viewDidLoad()
titleLabel?.text = "\(passedValue) Times Table"
}
}
I've followed tutorials but can't seem to solve the problem! Thanks for any help!
Replace
self.performSegue(withIdentifier: "pushSegue", sender: nil)
with
self.present(vc,animated:true,completion:nil)
or ( if the current vc is inside a naigation )
self.navigationController?.pushViewController(vc,animated:true)
Using
self.performSegue(withIdentifier: "pushSegue", sender: nil)
is fit with storyboards not xibs and if this your case then you need to use the above line only inside the button action with implementing this method inside the source vc
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pushSegue" {
if let nextViewController = segue.destination as? TimesTablesViewController{
nextViewController.passedValue = "xx"
}
}
}
I’m assuming that the new view controller is appearing, but you’re simply not seeing the data. If so, you’re evidently using storyboards. The TimesTablesViewController(nibName:bundle:) only works if you’re using XIB/NIBs and manually presenting new view controller.
If you’re really using storyboards, simplify your butClick method:
#IBAction func butClick(_ sender: UIButton) {
NSLog("Button Pressed")
performSegue(withIdentifier: "pushSegue", sender: self)
}
But implement prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? TimesTablesViewController {
destination.passedValue = "xx"
}
}
Assuming the above fixes your problem, I might suggest a further simplification. Notably, if your butClick(_:) method is really only calling performSegue, you can segue to this next scene without any #IBAction method at all:
remove butClick(_:) entirely;
remove the connection between the button and the butClick method in IB, on the “Connections Inspector” tab in the right panel; and
control-drag from the button previously hooked up to butClick(_:) to the scene for TimesTablesViewController.
That will simplify your code further.

UIViewControllers sharing 'generic' IBAction

I have an app with 6 UIViewControllers.
ANY viewcontroller features a function like this one:
#IBAction func onHelp(_ sender: UIBarButtonItem) {
DispatchQueue.main.async(execute: { () -> Void in
let helpVC = self.storyboard?.instantiateViewController(withIdentifier: "Help") as! HelpViewController
helpVC.starter = "MapHelp"
helpVC.helpSubtitle = "Map"
self.present(helpVC, animated: true, completion: nil)
})
}
Any IBAction in any viewcontroller presents the same HelpViewController but passing different parameters (starter and helpSubtitle).
Since I don't like to repeat code, first of all I thought this function should be converted to something more generic.
But: is there any way to create a generic IBAction, working for every viewcontroller?
Create a BaseViewController and add the generic method there.
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func genericMethod(starter: String, helpSubtitle: String){
let helpVC = self.storyboard?.instantiateViewController(withIdentifier: "Help") as! HelpViewController
helpVC.starter = starter
helpVC.helpSubtitle = helpSubtitle
self.present(helpVC, animated: true, completion: nil)
}
#IBAction func onHelp(_ sender: UIButton?) {
//You can use this method as generic IBaction if you want. It can be connected to buttons of all child View Controllers. But doing so will limit your param sending ability. On the plus side though, you won't have to define an IBAction everywhere and you can simply connect your child VC's button to Parent Class' IBAction.
}
}
Now inherit your ViewControllers from this class like:
import UIKit
class ViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnTapped(_ sender: Any) {
genericMethod(starter: "View Controller", helpSubtitle: "I was triggered from VC1")
}
}
and
import UIKit
class SecondViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func btnTapped(_ sender: Any) {
genericMethod(starter: "View Controller 2", helpSubtitle: "I was triggered from VC2")
}
}
That's it. Both your ViewControllers can call the parent method. If you still want to use the generic IBAction, you can do that too but I'd not recommend that course given that you want to pass params that can vary. If you wanted to do it though, it would look like this:
Bear in mind, the ViewController here has been inherited from the base ViewController which is why it can access the IBActions defined in the parent class. All you have to do is drag and connect.

Passing Data through multiple View Controllers with segue [Swift 3.0 Xcode]

NOTE: Question has been edited in an attempt to be more clear with my issue.
Hey, I am trying to pass data through multiple VCS. I want to pass data (arrays) from V2 -> V3 and then V3 -> V1 but I want to be able to only navigate through the VCs as such: V1 - V2 - V3 and V3 - V2 - V1.
So what I need to learn is how to pass data without navigating to a different VC as well as setting up two preparetosegue methods to pass data between V2 -> V3 and V3 -> V1 while also being able to navigate between all VCs. When I create my first preparetosegue, I am unable to use other segues associated in my VC to navigate to other VCs without getting a Fatal Error.
Can anyone help me?
Any input would be greatly appreciated!
Heres my attempt:
import UIKit
class ViewController: UIViewController {
var name = String()
var StopButInfo = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}
import UIKit
class SecondViewController: UIViewController {
var StringArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBOutlet var PHeight: UITextField!
#IBOutlet var PName: UITextField!
#IBAction func Search(_ sender: Any) {
if PHeight.text != ""{
performSegue(withIdentifier: "SearchSegue", sender: self)}
let CDstart = String(describing: Date())
StringArray.append(CDstart)
StringArray.append(PName.text!)
StringArray.append(PHeight.text!)
}
override func prepare(for SearchSegue: UIStoryboardSegue, sender: Any?){
let thirdController = SearchSegue.destination as! ThirdViewController
thirdController.SearchButInfo = StringArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class ThirdViewController: UIViewController {
var height = String()
var SearchButInfo = [String]()
var StringArray = [String]()
#IBAction func Stop(_ sender: Any) {
if StringArray.count != 0{
performSegue(withIdentifier: "SegueToStart", sender: self)
}
let CDStop = String(describing: Date())
StringArray.append(CDStop)
StringArray.append(height)
}
override func prepare(for SegueToStart: UIStoryboardSegue, sender: Any?){
let firstController = SegueToStart.destination as! ViewController
firstController.StopButInfo = StringArray}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to check which view controller's segue is about to be performed, this can be done like this inside prepare(for segueMVH: UIStoryboardSegue, sender: Any?) method:
if let firstController = segueMVH.destination as! FirstViewController {
// Set first view controller's data
} else if let secondController = segueMVH.destination as! SecondViewController {
// Set second view controller's data
} else if let thirdController = segueMVH.destination as! ThirdViewController {
// Set third view controller's data
}
Note: It's better to use a different identifier for each segue to be able to distinguish between them.
The error you got on let secondController = segueMVH.destination as! ThirdViewController is saying that you are casing HC.ViewController into ThirdViewController and that's why it failed. It means that the destination view controller of your segue is not ThirdViewController.
To further help you understand segue: A segue is a connection between a source view controller and a destination view controller and can be only used between them two. See this picture:
In this case, I have a segue connection in my storyboard connected between my VC1's button and VC2. In this case, my button click will trigger this segue and prepare(for segue) method can only be in VC1 where it passes data to VC2.
So in your situation, you believe that the destination of your segue is ThirdViewController but it's actually not. So please check your segue with identifier segueMVH to see if it is connected between your current view controller and your ThirdViewController.
Hope this helps

Delegate using Container View in Swift

I'm developing an app for iPad Pro. In this app, containerView use to add additional views and interact with them.
First, I created a protocol:
protocol DataViewDelegate {
func setTouch(touch: Bool)
}
Then, I created my first view controller
import UIKit
class ViewController: UIViewController, DataViewDelegate {
#IBOutlet var container: UIView!
#IBOutlet var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func setTouch(touch: Bool) {
if touch == true {
labelText.text = "Touch!"
}
}
}
And finally, I created a view that will be embedded in containerView.
import UIKit
class ContainerViewController: UIViewController {
var dataViewDelegate: DataViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func touchMe(sender: AnyObject) {
dataViewDelegate?. setTouch(true)
}
}
But for some reason, nothing happened, the first view controller receives nothing in setTouch function.
My question is: In this case, using container, how can I make the communication between two ViewsControllers?
Like #nwales said you haven't yet set the delegate. You should do set the delegate in prepareForSegue function on your first viewController (who contain the viewContainer)
First select the embed segue and set an identifier in the attributes inspector.
Then in the parentViewController implement the func prepareForSegue like this:
Swift 4+:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "the identifier") {
let embedVC = segue.destination as! ViewController
embedVC.delegate = self
}
}
Below:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "the identifier") {
let embedVC = segue.destinationViewController as! ContainerViewController
embedVC.dataViewDelegate = self
}
}
Looks like you defined the delegate, but have not set the delegate. This happens to me all the time.

How to hide and show label when navigation VC1 to VC2 back and forth

Say, I have a label show : Loading...
problem: When return from VC(2). The label is not hidden.
How to hide it when return from VC(2) and dont hide it when in navigating to VC(2) and show the message : Loading....
in VC(1)
#IBOutlet weak var lbLoadingMsg
In viewDidLoad() {
lbLoadingMsg.hidden = true
}
-2-- turn it on when prepare to navigate to VC(2)
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool
{
--code--
lbLoadingMsg.hidden = false
}
Override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
}
You can use NSNotificationCenter for that.
Follow this simple steps:
1.In your VC(2) add this code into your button from where you are going back:
#IBAction func goBack(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("hide", object: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
2.In your First View add this code into viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hideLabel:", name:"hide", object: nil)
}
now this method will call this function:
func hideLabel(notification: NSNotification){
self.lbLoadingMsg.hidden = true
}
And this will hide your label in first view when ever goBack button will pressed from first view.
Hope this will help you.
Write this in VC2
,
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var identifier = segue.identifier
if(identifier! == "yourIdentifier"){
var vc1:VC1 = segue.destinationViewController as! VC1
vc1.lbLoadingMsg.hidden = true
}
}
func viewDidAppear(_ animated: Bool) {
lbLoadingMsg.hidden = true
}
Move
lbLoadingMsg.hidden = true
line from viewDidLoad to viewDidAppear. I think most quicker way.