Swift navigate back from view2 to view1 - ios

I have View1 in which button has title and I did successful segue to View2 with passing the Button title String which will be assigned to View 2 Button also.
Now when user go back from View2 to View1 , View1 Button has no value. How can I pass button value to View1?
I tried delegate method.. But no success :
Edited
View1
class PatientBreifInfoViewController: UIViewController, TasksViewDelegate {
var passName: String!
#IBOutlet weak var patientName: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
patientName.setTitle(passName, forState: .Normal)
}
func setName(name: String) {
patientName.setTitle(name, forState: .Normal)
print("View1")
print(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "toTasks") {
let controller = segue.destinationViewController as! TasksViewController
controller.delegate = self
controller.passName = passName
}
}
}
View2
protocol TasksViewDelegate: class {
func setName(patientName: String)
}
class TasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var passName : String!
#IBOutlet weak var backButton: UIButton!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var patientName: UIButton!
weak var delegate: TasksViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
patientName.setTitle(passName, forState: .Normal)
}
#IBAction func backButton(sender: AnyObject) {
delegate!.setName(passName)
self.navigationController?.popViewControllerAnimated(true)
}
}

Your protocol and delegate should work fine. However, you implementation of setName in ViewController1 is not using the Name parameter passed into it however:
func setName(Name: String)
{
passName = patientName
}
Should be changed to something like:
func setName(Name: String)
{
patientName = Name
}
You should also follow the swift naming convention of variables, parameters and functions starting with lowercase names and types beginning with uppercase names. So should be setName(name: String) not setName(Name: String) which would also mean changing patientName = Name to patientName = name in the example.
Update
Because your view controller will stay in memory while ViewController2 is on screen viewDidLoad will not get called again when transitioning from ViewController2 to ViewController1. Instead, you can set the button's title directly in your delegate method. For example:
func setName(name: String)
{
patientName.setTitle(name, forState: .Normal)
}

popViewController(animated:) removes/pops current view controller from navigation stack. Now you can use first view controller of navigation stack to access its members. You may not need to use delegate here
Try this and see:
class TasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBAction func backButton(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
if let pbiViewController = self.navigationController?.viewControllers.first as? PatientBreifInfoViewController {
pbiViewController.passName = passName
}
}
}
class PatientBreifInfoViewController: UIViewController {
var passName: String?
}

Related

Why do I have to call my protocol functions two times to make it work?

I'm currently building a simple app to learn the protocol - delegate functionality. However my code doesn't work, even after I edited the way I did in my first practice app where it worked. In the FirstViewController there is a UILabel and a UIButton. When the user taps on the UIButton, a segue brings them to the SecondViewController where they should enter their name into a UITextField. After that, they can press the UIButton in the SecondViewController and the entered Name should be displayed in the UILabel in the FirstViewController.
I can't figure out why I have to call the protocol function two times in the #IBAction backButtonPresses(). Also, I can't figure out how to handle the same protocol function in the FirstViewController.
Here's the code for the FirstViewController.swift file:
import UIKit
class FirstViewController: UIViewController, SecondViewControllerDelegate {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var button: UIButton!
var labelText = ""
let secondVC = SecondViewController()
func changeLabelText(name: String) {
labelText = secondVC.enteredName
}
#IBAction func buttonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecondVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as? SecondViewController
destinationVC?.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = secondVC.enteredName
}
}
And here's the code of the secondViewController:
import UIKit
protocol SecondViewControllerDelegate {
func changeLabelText(name: String)
}
class SecondViewController: UIViewController, SecondViewControllerDelegate {
var delegate: SecondViewControllerDelegate?
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var backButton: UIButton!
var enteredName: String = ""
func changeLabelText(name: String) {
enteredName = name
}
#IBAction func backButtonPressed(_ sender: UIButton) {
changeLabelText(name: nameTextField.text ?? "")
delegate?.changeLabelText(name: nameTextField.text ?? "")
print("das ist der name \(enteredName)")
dismiss(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
You do not call any delegate method twice in backButtonPressed. You are calling two completely different changeLabelText methods. One is in SecondViewController, the other is on the delegate.
The call to changeLabelText in the SecondViewController is quite unnecessary. In fact, the enteredName property in SecondViewController is unnecessary. Also, SecondViewController should not be implementing its own delegate.
The call to changeLabelText on delegate is all you need. You just need to update the implementation of changeLabelText in FirstViewController to update the label's text with the new value.
func changeLabelText(name: String) {
nameLabel.text = name
}
Do not reference the secondVC property in FirstViewController. In fact, remove that property completely. It's not needed and it's referencing a completely different instance of SecondViewController than the one you actually present via segue.
I also suggest renaming the delegate method from changeLabelText to something more general such as enteredText. SecondViewController can be used by any other view controller to obtain some text. It's not specific to changing a label.
Here's your two view controllers with suggested changes:
class FirstViewController: UIViewController, SecondViewControllerDelegate {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var button: UIButton!
func enteredText(name: String) {
nameLabel.text = name
}
#IBAction func buttonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecondVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as? SecondViewController
destinationVC?.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
protocol SecondViewControllerDelegate {
func enteredText(name: String)
}
class SecondViewController: UIViewController {
var delegate: SecondViewControllerDelegate?
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var backButton: UIButton!
#IBAction func backButtonPressed(_ sender: UIButton) {
let name = nameTextField.text ?? ""
delegate?.changeLabelText(name: name)
print("das ist der name \(name)")
dismiss(animated: true)
}
}

passing data to a specific label in another view controller, depending on the button pressed

I'm just starting out with swift and decided to create a calorie counting app to test my skills in which I am using an Api to get the nutrition data.
Pressing the add breakfast/lunch/dinner segues to a search view controller from which I pass the calories back.
I am using protocol delegate design pattern. I wanted to know how I could set it up so that when I press the add breakfast button, only the breakfast calorie label is updated and when I press add lunch or dinner, their calorie labels are updated accordingly. any help would be greatly appreciated! I posted the codes of my logViewController and SearchViewController
import UIKit
protocol DataDelegate {
func updateLogCalories(str: String?)
}
class SearchViewController: UIViewController,UITextFieldDelegate,CalorieManagerDelegate{
var delagate: DataDelegate?
#IBOutlet weak var searchTF: UITextField!
#IBOutlet weak var calorieLabel: UILabel!
#IBOutlet weak var foodNameLabel: UILabel!
var calorieManager = CalorieManager()
var logCals : String?
override func viewDidLoad() {
super.viewDidLoad()
calorieManager.delegate=self
searchTF.delegate=self
}
#IBAction func searchPressed(_ sender: Any) {
searchTF.endEditing(true)
print(searchTF.text!)
}
#IBAction func addButtonPressed(_ sender: UIButton) {
delagate?.updateLogCalories(str: logCals)
self.dismiss(animated: true, completion: nil)
}
class LogViewController: UIViewController{
var breakfastCal: String?
#IBOutlet weak var breakfastLabel: UILabel!
#IBOutlet weak var lunchLabel: UILabel!
#IBOutlet weak var totalCaloriesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navController = segue.destination as! UINavigationController
let destController = navController.topViewController as! SearchViewController
destController.delagate = self
}
#IBAction func addBreakfastPressed(_ sender: UIButton) {
}
#IBAction func addLunchPressed(_ sender: UIButton) {
}
}
extension LogViewController: DataDelegate{
func updateLogCalories(str: String?) {
breakfastLabel.text = str
}
}
If all of your buttons (breakfast, lunch, and dinner) trigger the addButtonPressed action, you need a way to tell which button was pressed, and a way to pass that information to the DataDelegate.
I suggest you put your buttons into an array:
#IBOutlet weak var breakfastButton: UIButton!
#IBOutlet weak var lunchButton: UIButton!
#IBOutlet weak var dinnerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Populate our array of buttons so we can search for a button
buttons = [breakfastButton, lunchButton, dinnerButton]
}
Then modify your DataDelegate protocol to include a meal enum:
enum Meal: Int {
case breakfast = 0
case lunch = 1
case dinner = 2
}
protocol DataDelegate {
func updateLogCalories(str: String?, forMeal meal: Meal)
}
And set up your DataDelegate to implement the new method:
class MyDataDelegate: DataDelegate {
func updateLogCalories(str: String?, forMeal meal: Meal) {
let str = str ?? ""
print("updating calories with string \(str) for meal \(meal)")
}
}
Now modify your addButtonPressed method so it searches the array to figure out which button was pressed.
#IBAction func addButtonPressed(_ sender: UIButton) {
if let index = buttons.firstIndex(of: sender),
let meal = Meal(rawValue: index) {
print("Button at index \(index) pressed")
delegate.updateLogCalories(str: nil, forMeal: meal)
} else {
print("Can't find button or can't create enum.")
}
}

How to pass data using delegates and protocols

I have this first viewController which has UILabel in it and secondViewController which has UItextField and Add button. They are embedded in tabbar. I want to pass data from text field when add button is clicked to uilabel of first view controller.
protocol SendDelagate
{
func setData(string:String)
}
First View Controller is
class ViewController: UIViewController,SendDelagate{
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let vc = SecondViewController()
vc.delegates = self
}
func setData(string: String) {
label.text = string
}
}
And second ViewController is
class SecondViewController: UIViewController {
var delegates:SendDelagate?
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addButton(_ sender: UIButton) {
let text = textField.text!
delegates?.setData(string: text)
}
}
SecondViewController is embedded in UITabbarController?
You can find SecondViewController instance via TabbarController
class ViewController: UIViewController, SendDelagate {
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let secondViewController = tabBarController?.viewControllers?.first(where: { $0 is SecondViewController }) as? SecondViewController {
secondViewController.delegates = self
}
}
func setData(string: String) {
label.text = string
}
}
You can use User Defaults. So you save with your Add Button into User Defaults, and on viewDidLoad on the other view, you can load it.

Delegate data from one UIViewController to another one

I am completely new to Swift programming and tried to delegate a single String from one ViewController to another by clicking a send button. The problem is , that it does not work ...
I guess it would be easy for you to solve this and considering that it would be very helpful wether you explain me what I did wrong. :)
Thank you a lot
import UIKit
protocol protoTYdelegate {
func didSendMessage(message: String)
}
class New: UIViewController {
#IBOutlet weak var SendButton: UIButton!
var tydelegate: protoTYdelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func SendButtonAction(_ sender: Any) {
let nachricht = "It works fine."
tydelegate?.didSendMessage(message: nachricht)
}
}
import UIKit
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let controller = New()
controller.tydelegate = self
}
}
extension ThankYouPage: protoTYdelegate{
func didSendMessage(message: String) {
numbersView.text = message
}
As far as I understand, this code block doesn't work but the problem is not in the code, it's actually way that you choose to send data. In iOS development, there are many ways to send data. In your case, you need to use prepareForSegue method to send data to new class, not necessary to use delegates.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ThankYouPage") {
let vc = segue.destination as! ThankYouPage
vc.message = "Message that you want to send"
}
}
And you need to implement your ThankYouPage as:
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
var message = ""
override func viewDidLoad() {
super.viewDidLoad()
numbersView.text = message
}
}
In addition to that, you can use didSet method to print out the message to label instead of printing it directly in viewDidLoad method. Simply:
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
var message: String?{
didSet{
numbersView.text = message
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
I hope this helps you.
#Eyup Göymen's answer is right.
I have another way, assuming that you are not using segue and you are pushing to next controller by manual-code.
So your ThankYouPage code should be like :
import UIKit
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func someButtonAction(_ sender: Any) { // By clicking on some, you are opening that `New` controller
let detailView = self.storyboard?.instantiateViewController(withIdentifier: "New") as! New
detailView.tydelegate = self
self.navigationController?.pushViewController(detailView, animated: true)
}
}
extension ThankYouPage: protoTYdelegate {
func didSendMessage(message: String) {
numbersView.text = message
}
}

Segue anachronism

I am trying to pass text input from the following ViewController:
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var inputField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
inputField.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
inputField.resignFirstResponder()
}
func textFieldDidEndEditing(inputField: UITextField) {
let info = inputField.text
performSegueWithIdentifier("goToBlue", sender: info)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goToBlue" {
if let blueVC = segue.destinationViewController as? BlueViewController {
if let sentValue = sender as? String {
blueVC.receptacle = sentValue
print(blueVC.receptacle)
}
}
}
}
}
To this ViewController:
class BlueViewController: UIViewController {
#IBOutlet weak var blueText: UILabel!
var receptacle = "fail"
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print(receptacle)
blueText.text = receptacle
print(receptacle)
}
}
The print statement in the first ViewController outputs correctly, however the output for the print statements in the second ViewController is fail fail, and the label in the second view reads "fail".
Due to this, I have reason to believe this is a timing issue.
Am I right? How do I fix this?
If you want to trigger your segue programmatically, you need to wire your goToBlue segue from the ViewController icon of your from ViewController to the BlueViewController:
Remember to set the Identifier of the Storyboard Segue in the Attributes Inspector to goToBlue.

Resources