The data I entered in the TextField does not transfer to another label - ios

Hello guys can you help me, I have an app that has two ViewController and in the first VC I have four empty TextField and at the second VC I have four empty Labels that should receive new information and show I the label but my code doesn't work so could you help with this problem, I think something not right with my personalData
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var name: UITextField!
#IBOutlet weak var age: UITextField!
#IBOutlet weak var city: UITextField!
#IBOutlet weak var mail: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)
}
#objc func edit() {
print("Edit is done")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "personalData" else { return }
guard let destination = segue.destination as? SecondViewController else { return }
destination.personalData = name.text ?? ""
destination.personalData = age.text ?? ""
destination.personalData = city.text ?? ""
destination.personalData = mail.text ?? ""
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
//////////////////////////////////////
import UIKit
class SecondViewController: UIViewController {
struct User{
}
var personalData = ""
override func viewDidLoad() {
super.viewDidLoad()
firstProfileLabel.text = personalData
secondProfileLabel.text = personalData
thirdProfileLabel.text = personalData
lastProfileLabel.text = personalData
print("SecondVC", #function)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit,
target: self,
action: #selector(edit))
}
#objc func edit() {
print("Edit is done")
}
#IBOutlet weak var firstProfileLabel: UILabel!
#IBOutlet weak var secondProfileLabel: UILabel!
#IBOutlet weak var thirdProfileLabel: UILabel!
#IBOutlet weak var lastProfileLabel: UILabel!
}
My mentor said that "The problem is with the variable personalData. The variable is of the stripe type and can store only one value.
If you want to pass values through a variable and not directly, you can create a structure, e.g. User with variables Name, Age, City, etc., and make personalData a User type and empty array."
But I don't understand how exactly I should write it in code.

Start simple. Give your second view controller separate properties for each value you want to pass:
class SecondViewController: UIViewController {
var name: String
var age: String
var city: String
var mail: String
}
Then in your first view controller's perpare(for:) method, set each of those variables separately:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "personalData" else { return }
guard let destination = segue.destination as? SecondViewController else { return }
destination.name = name.text ?? ""
destination.age = age.text ?? ""
destination.city = city.text ?? ""
destination.mail = mail.text ?? ""
}
And rewrite your second view controller's viewDidLoad method to install each property into the correct field.
Once you've got that working, you can figure out how to instead pass all the string values in a single structure.
Hint:
Create a struct called something like UserInfo:
struct UserInfo {
let name: String
let age: String
let city: String
let mail: String
}
And then give your second view controller a property of type UserInfo, and set that in prepare(for:)

Related

How can I pass dictionary from one view controller class to another?SWIFT

I am trying to make a list of users and their passwords in one view controller, save that information in a dictionary, and send that dictionary to another view controller which asks the user to input their username/password combination to authorize the log in. (the key is the username and the value is the password). Is there a way I can send the dictionary from SecondVC to the FirstVC?
First View Controller
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var Username: UITextField!
#IBOutlet weak var Verification: UILabel!
#IBOutlet weak var Password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Username.delegate = self
Password.delegate = self
}
var usersDict = [String : String]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let des = segue.destination as? AccountViewController {
des.usersDict = usersDict
}
}
#IBAction func Authorization(_ sender: Any) {
for ( key , value ) in usersDict{
let v = key.count
var start = 0
if start <= v{
if Username.text == key{
if Password.text == value{
Verification.text = "Looks Good"
}
}
else{
start += 1
}
}
else{
Verification.text = "Yikes"
}
}
}
}
Second View Controller
class AccountViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var CreateUsername: UITextField!
#IBOutlet weak var CreatePassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
CreateUsername.delegate = self
CreatePassword.delegate = self
// Do any additional setup after loading the view.
}
var usersDict = [ String : String ]()
#IBAction func MakeANewAccount(_ sender: Any) {
usersDict[CreateUsername.text!] = CreatePassword.text!
}
}
I have made there dictionary, but it will only send in the beginning and won't update after creating the original account. (dictionary it is sending is empty)
With a segue add this method inside ViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let des = segue.destination as? AccountViewController {
des.usersDict = yourDicHere
}
}
Here's a general pattern for making a controller work with data from some object it creates, in this case a second controller.
Try applying it to your situation and let me know if you run into problems.
protocol Processor {
func process(_ dict: [String : String])
}
class FirstController: UIViewController, Processor {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? SecondController {
controller.delegate = self
} else {
print("Unexpected view controller \(segue.destination)")
}
}
func process(_ dict: [String : String]) {
}
}
class SecondController: UIViewController {
var delegate: Processor?
func someWork() {
if let processor = delegate {
processor.process(["Name" : "Pwd"])
} else {
print("Delegate not assigned")
}
}
}

How to pass data from view controller to other view controller [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 2 years ago.
iā€™m newbie in swift language and i want to pass the price from the Item view controller to other controller (Payment view controller) using array. Can anyone help me? Thank you
Here the code for the item detail view controller
import UIKit
class ItemDetailViewController: UIViewController {
var items = [item]()
var name : String = ""
var price : String = ""
var imagee : String = ""
#IBOutlet weak var labelname: UILabel!
#IBOutlet weak var image: UIImageView!
#IBOutlet weak var labelprice: UILabel!
// This one got error.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
var DestViewController : PaymentViewController = segue.destination as! PaymentViewController
DestViewController.price = labelprice?[IndexPath.text]
}
#IBAction func addtoPayment(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
labelname.text = name
labelprice.text = price
image.image = UIImage(named: imagee)
}
}
And here the code for the payment
import UIKit
class PaymentViewController: UIViewController {
var items = [item]()
var price : String = ""
#IBOutlet weak var paymentdetails: UILabel!
#IBOutlet weak var cardnametextfield: UITextField!
#IBOutlet weak var validthrutextfield: UITextField!
#IBOutlet weak var cardnumbertextfield: UITextField!
#IBOutlet weak var cvcnumbertextfield: UITextField!
#IBOutlet weak var labelprice: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
labelprice.text = price
// Do any additional setup after loading the view.
}
#IBAction func paybutton(_ sender: Any) {
if cardnametextfield.text == "" {
alertMessage(titleInput: "Error, Payment Unsuccessful!", messageInput: "Please Fill all the fields")
} else if validthrutextfield.text == "" {
alertMessage(titleInput: "Error, Payment Unsuccessful!", messageInput: "Please Fill all the fields")
} else if cardnumbertextfield.text == "" {
alertMessage(titleInput: "Error, Payment Unsuccessful!", messageInput: "Please Fill all the fields")
} else if cardnumbertextfield.text == "" {
alertMessage(titleInput: "Error, Payment Unsuccessful!", messageInput: "Please Fill all the fields")
} else {
alertMessage(titleInput: "Success!", messageInput: "Payment Successful!")
self.transitionToHomePage()
}
}
func alertMessage(titleInput: String, messageInput: String){
let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertController.Style.alert)
let paybutton = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(paybutton)
self.present(alert, animated: true, completion: nil)
}
func transitionToHomePage(){
let TabHomeViewController = storyboard?.instantiateViewController(identifier: Constrants.Storyboard.TabHomeViewController) as? UITabBarController
view.window?.rootViewController = TabHomeViewController
view.window?.makeKeyAndVisible()
}
}
you can use this code ... try to use first letter small for objects
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
var destViewController : PaymentViewController = segue.destination as! PaymentViewController
if let lText = labelprice?.text {
destViewController.price = lText
}
}
If you want to unwrap:
DestViewController.price = labelprice?.text ?? ā€œā€
This way is not recommended but you can use
DestViewController.price = labelprice!.text
Search for unwarp in Swift

How to send data from TextField from second view controller to first view controller and add this data to array swift iOS [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 3 years ago.
I want to send data from TextField from second view controller to first view controller and add this data to an array
I have a struct which I will save to array:
struct ContactsModel {
var name : String
var surname : String
var phoneNumber : String
}
first VC:
class FirstViewController: UIViewController {
var contacts : [ContactsModel] = []
}
second VC:
class SecondViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var surnameTextField: UITextField!
#IBOutlet weak var phoneNumberTextField: UITextField!
#IBAction func saveAndClose(_ sender: UIButton) {
// here i want to send this objects (nameTextField, surnameTextField, phoneNumberTextField) in array in first VC when i press this button
}
}
You can accomplish this using a delegate:
struct ContactsModel {
var name : String
var surname : String
var phoneNumber : String
}
protocol SecondViewControllerDelegate: class {
func savedAndClosed(with model: ContactsModel)
}
class FirstViewController: UIViewController {
var contacts : [ContactsModel] = []
// Whereever you create and present your instance of SecondViewController make it conform to the delegate
func showSecondVC() {
let secondVC = SecondViewController()
secondVC.delegate = self
present(secondVC, animated: true, completion: nil)
}
}
extension FirstViewController: SecondViewControllerDelegate {
func savedAndClosed(with model: ContactsModel) {
contacts.append(model)
}
}
class SecondViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var surnameTextField: UITextField!
#IBOutlet weak var phoneNumberTextField: UITextField!
weak var delegate: SecondViewControllerDelegate?
#IBAction func saveAndClose(_ sender: UIButton) {
// here i want to send this objects (nameTextField, surnameTextField, phoneNumberTextField) in array in first VC when i press this button
guard let name = nameTextField.text, let surname = surnameTextField.text, let phoneNumber = phoneNumberTextField.text else { return }
let new = ContactsModel(name: name, surname: surname, phoneNumber: phoneNumber)
delegate?.savedAndClosed(with: new)
}
}
First be sure to make var contacts in FirstViewController static:
class FirstViewController: UIViewController {
static var contacts : [ContactsModel] = []
}
Then in SecondViewController you can edit variable "contacts" like this:
class SecondViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var surnameTextField: UITextField!
#IBOutlet weak var phoneNumberTextField: UITextField!
#IBAction func saveAndClose(_ sender: UIButton) {
// here i want to send this objects (nameTextField, surnameTextField, phoneNumberTextField) in array in first VC when i press this button
FirstViewController.contacts.append(ContactsModel(name: nameTextField.text ?? "defaultName", surname: surnameTextField.text ?? "defaultSurname", phoneNumber: phoneNumberTextField.text ?? "defaultPhone"))
}
}
You need to define default values so even if text from field would be nil your app won't crush, in example we set default values here:
name: nameTextField.text ?? "defaultName"

Delegate is still nil

I am passing user data from a view controller called CreateNewAccount to another view controller called ThanksForJoining. For some reason my delegate is nil. I am using a segue in order to set my vc.delegate to self (= self) and the segue identifier "thanksForJoining" refers to the segue that connects CreateNewAccount to ThanksForJoining on the storyboard. Somehow though, the delegate remains nil.
CreateNewAccount:
import UIKit
protocol UserInfoDelegate {
func sendUserInfo(firstName: String, lastName: String, username: String, password: String)
}
class CreateNewAccount: UIViewController{
#IBOutlet weak var FNInput: UITextField!
#IBOutlet weak var LNInput: UITextField!
#IBOutlet weak var usernameInput: UITextField!
#IBOutlet weak var passwordInput: UITextField!
var infoDelegate: UserInfoDelegate?
#IBAction func sendInfo(_ sender: Any) {
if(infoDelegate != nil){
if(FNInput.text != nil && LNInput.text != nil && usernameInput.text != nil && passwordInput.text != nil){
let firstName = FNInput.text
let lastName = LNInput.text
let username = usernameInput.text
let password = passwordInput.text
infoDelegate?.sendUserInfo(firstName: firstName!, lastName: lastName!, username: username!, password: password!)
}
}
}
}
ThanksforJoining:
import UIKit
class ThanksForJoining: UIViewController, UserInfoDelegate {
#IBOutlet weak var fName: UILabel!
func sendUserInfo(firstName: String, lastName: String, username: String, password: String) {
print(firstName)
fName.text = firstName
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "thanksForJoining") {
let createNewAccount: CreateNewAccount = segue.destination as! CreateNewAccount
createNewAccount.infoDelegate = self
}
}
}
First of all, you need to confirm that:
You connected CreateNewAccount to ThanksForJoining via a segue.
The segue's Identifier is set to thanksForJoining correctly
(Be careful about the letter cases.)
If any of the two is not true, you have lost a little time and I have lost my time to prepare for a big typhoon. Update your question to clarify what's happening and wait for someone to help you...
Assuming two things above, prepare(for:sender:) is called on the source view controller. You need to implement it in your CreateNewAccount class.
CreateNewAccount:
import UIKit
class CreateNewAccount: UIViewController {
#IBOutlet weak var firstNameInput: UITextField!
#IBOutlet weak var lastNameInput: UITextField!
#IBOutlet weak var usernameInput: UITextField!
#IBOutlet weak var passwordInput: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "thanksForJoining" {
let destinationVC = segue.destination as! ThanksForJoining
if
let firstName = firstNameInput.text, !firstName.isEmpty,
let lastName = lastNameInput.text, !lastName.isEmpty,
let username = usernameInput.text, !username.isEmpty,
let password = passwordInput.text, !password.isEmpty
{
destinationVC.receiveUserInfo(firstName: firstName, lastName: lastName, username: username, password: password)
}
}
}
}
ThanksForJoining:
import UIKit
class ThanksForJoining: UIViewController {
var firstName: String?
#IBOutlet weak var firstNameLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
firstNameLabel.text = firstName
}
func receiveUserInfo(firstName: String, lastName: String, username: String, password: String) {
print(firstName)
self.firstName = firstName
}
}
Seems delegate pattern is sort of too much for your purpose and you just need to define a data passing method in the destination view controller ThanksForJoining.
I assume you have connected your segue from some button of your CreateNewAccount. If the segue is connected from the view controller (not from a button), the code above needs small modification.
But anyway, in your original code, the method prepare(for:sender:) in ThanksForJoining would never be called, so the delegate would never be set. Thus, the delegate remains nil.
First you need a reference to the CreateNewAccount class in the class ThanksForJoining class. Then you need to activate the delegate by setting it equal to self in the ThanksForJoing class in viewDidLoad.
class ThanksForJoining: UIViewController, UserInfoDelegate {
var createNewAccount: CreateNewAccount?
override func viewDidLoad() {
super.viewDidLoad()
createNewAccount?.infoDelegate = self
}
{
Then your delegate methods will work.
The only possible issue is segue identifier mismatch in code and storyboard
In the story board, select the segue between two VCs
And then go the attributes inspector and set the ID "thanksForJoining" in "Identifier" field
Some suggestions
If your intention is to check whether user has entered all the fields before sending the data back, then this code will serve the purpose better
if (infoDelegate != nil) {
if let firstName = FNInput.text, firstName.count>0,
let lastName = LNInput.text, lastName.count>0,
let username = usernameInput.text, username.count>0,
let password = passwordInput.text, password.count>0 {
infoDelegate?.sendUserInfo(firstName: firstName, lastName: lastName, username: username, password: password)
}
}

Unresolved identifier using segue when passing data

In my app I am using segue to pass data between two viewcontrollers and that should be easy enough, but for som reason I can`t see there I keep getting "Unresolved Identifier"
Her are some of the code that has to do with that function.
from ViewController 1
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet var panelWidthTextField: UITextField!
#IBOutlet var panelHightTextField: UITextField!
#IBOutlet var panelsWideTextField: UITextField!
#IBOutlet var panelsHightTextField: UITextField!
#IBOutlet var panelPitchTextField: UITextField!
#IBOutlet var calculateButton: UIButton!
#IBOutlet var resultWithLabel: UILabel!
#IBOutlet var resultHightLabel: UILabel!
#IBOutlet var fillAllFieldsLabel: UILabel!
var pawidth:String!
var pahight:String!
var papitch:String!
override func viewDidLoad()
{
super.viewDidLoad()
panelWidthTextField.text = pawidth
panelHightTextField.text = pahight
panelPitchTextField.text = pap itch
From Second ViewController
import UIKit
import CoreData
class DataBase: UIViewController, UITextFieldDelegate
{
#IBOutlet var makerTextField: UITextField!
#IBOutlet var modelTextField: UITextField!
#IBOutlet var stPanelWidthTextField: UITextField!
#IBOutlet var stPanelHightTextField: UITextField!
#IBOutlet var stPitchTextField: UITextField!
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// Removes keyboard when touch outside edit field.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
#IBAction func saveButton(sender: UIButton)
{
let ed = NSEntityDescription.entityForName("Ledinfo", inManagedObjectContext: moc)
let model = Ledinfo(entity:ed!, insertIntoManagedObjectContext:moc)
model.manufactor = makerTextField.text
model.model = modelTextField.text
model.panelwidth = stPanelWidthTextField.text
model.panelhight = stPanelHightTextField.text
model.pitch = stPitchTextField.text
do {
try moc.save()
makerTextField.text = ""
modelTextField.text = ""
stPanelWidthTextField.text = ""
stPanelHightTextField.text = ""
stPitchTextField.text = ""
Alert.show("Succsess", message: "Your Record Is Saved", vc: self)
}
catch _ as NSError
{
Alert.show("Failed", message: "Something Went Wrong", vc: self)
}
}
#IBAction func searchButton(sender: UIButton)
{
let ed = NSEntityDescription.entityForName("Ledinfo", inManagedObjectContext: moc)
let req = NSFetchRequest()
req.entity = ed
let cond = NSPredicate(format: "manufactor = %#", makerTextField.text!)
req.predicate = cond
do {
let result = try moc.executeFetchRequest(req)
if result.count > 0
{
let model = result[0] as! Ledinfo
makerTextField.text = model.manufactor
modelTextField.text = model.model
stPanelWidthTextField.text = model.panelwidth
stPanelHightTextField.text = model.panelhight
stPitchTextField.text = model.pitch
} else
{
Alert.show("Failed", message: "No Record Is Found", vc: self)
}
} catch _ as NSError!
{
Alert.show("Failed", message: "No Record Is Found" , vc: self)
}
}
#IBAction func transfereButton(sender: UIButton) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "transfereButton") {
let svc = segue.destinationViewController as! ViewController
svc.pawidth = stPanelWidthTextField.text
svc.pahight = stPanelHightTextField.text
svc.papitch = stPitchTextField.text
}
}
}
It can not find panelWidthTextField.text, panelHightTextField.text and panelPitchTextField.text as identifier.
I have check spelling and just can`t seem to be able to find what is missing.
Any help is appreciated
"Segue" means, that in "prepareForSegue" method you set the property of ViewController to some data in your DataBase controller. In your example, this can be done like this:
svc.pawidth = someDataFromDataBaseWhichYouWantToPassToSecondVC
svc.pahight = someDataFromDataBaseWhichYouWantToPassToSecondVC
svc.papitch = someDataFromDataBaseWhichYouWantToPassToSecondVC
And then, you can manipulate this data from your ViewController class.
You mistake that you are not passing the data from one VC to another, instead of that you are trying to set the property of 1stVC to another property of 1stVC, and there is no segue needed.
This has nothing to do with segues. do you have 3 text fields in your DataBase class with names panelWidthTextField, panelHightTextField and panelPithcTextField? It's complaining about not being able to find those variables.
You should call the performSegueWithIdentifier("transfereButton", sender: nil) inside your transfereButton IBOutlet action to actually make the prepareForSegue to run.

Resources