Adding things to NSUserDefaults - multiple views - ios

I am creating a dictionary-like app and I want to store the user's search history using NSUserDefaults. I created a seaechHistory array outside the class. Now I am appending the searchHistory array and save it using NSUserDefaults in willSelectRowAtIndexPath, and I retrieve the stored history in a history view. The storage worked fine but when I re-run the app the NSUserDefaults set the seachHistory to the empty array and thus I lost all the saved data. The synchronize() method does work anywhere.
Initial View Controller:
import UIKit
var searchHistory = [String]()
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet var textField: UITextField!
#IBAction func textFieldDidChange(sender: AnyObject) {
tableView.hidden = false
searchManager.updateFilter(textField.text)
tableView.reloadData()
}
#IBAction func tapOnTextField(sender: AnyObject) {
let textFieldLength = count(textField.text)
if textFieldLength == 0 {
tableView.hidden = true
} else {
tableView.hidden = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
textField.backgroundColor = UIColor.whiteColor()
tableView.hidden = true
self.textField.delegate = self
}
var searchManager = SearchManager()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchManager.filteredURLCount()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel!.text = searchManager.filteredURLAtIndex(indexPath.row)
return cell
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
self.textField.text = searchManager.filteredURLAtIndex(indexPath.row)
searchHistory.append(textField.text)
NSUserDefaults.standardUserDefaults().setObject(searchHistory, forKey: "History")
self.performSegueWithIdentifier("cellTapped", sender: "Cell")
textField.text = nil
tableView.hidden = true
textField.resignFirstResponder()
return indexPath
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
self.tableView.hidden = true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "cellTapped" {
var DestViewController: definitionView = segue.destinationViewController as! definitionView
DestViewController.searchWord = textField.text
}
}
}
History View Controller:
import UIKit
class historyView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
searchHistory = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
println(searchHistory)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destination: ViewController = segue.destinationViewController as! ViewController
}
}

You can read your array in viewDidLoad() method, then it won't be empty.
Add tihs code in your ViewController:
override func viewDidLoad() {
super.viewDidLoad()
searchHistory = NSUserDefaults.standardUserDefaults().objectForKey("History")! as! [String]
}
It should work.

Related

Sending data of UISwitch from one view controller to another?

I am creating an application where the user adds a person on the application and after that it right the amount of money they owe that person or that person owes him/her. So while coding I had a set of questions so it would be really helpful if you can help me.
Question 1: I have used UISwitch to know if user owes or the other person owes. So, depending on switch on and off the amount will have negative value if user owes and positive if other person owes. Also, the value is shown on other viewcontroller so how do I pass the state of UISwitch and how do I make the value negative and positive depending on the UISwitch's result?
Question 2: I want to show the balance(So the owes of user to that person would sum up and display) of the user in the title of Navigation Controller so how do it?
ViewControllers:
NewOwedDetailViewController: This is where I store new owe details of the person
Code:
import UIKit
class NewOwedDetailViewController: UIViewController {
#IBOutlet weak var titleTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var datePicker: UIDatePicker!
var person: People?
var owe: Owe?
override func viewDidLoad() {
super.viewDidLoad()
titleTextField.delegate = self as UITextFieldDelegate
locationTextField.delegate = self as UITextFieldDelegate
amountTextField.delegate = self as UITextFieldDelegate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
titleTextField.resignFirstResponder()
locationTextField.resignFirstResponder()
amountTextField.resignFirstResponder()
}
#IBAction func saveOwe(_ sender: Any) {
let name = titleTextField.text
let location = locationTextField.text
let amountText = amountTextField.text ?? ""
let amount = Double(amountText) ?? 0.0
let date = datePicker.date
if let owe = Owe(name: name, location: location, amount: amount, date: date) {
person?.addToRawOwes(owe)
//Below try function code has save() as throw function so whenever throw function are there you just add try at the beggining of the function
do {
try owe.managedObjectContext?.save()
self.navigationController?.popViewController(animated: true)
} catch {
print("Owe details could not be created")
}
}
}
#IBAction func oweSwitch(_ sender: UISwitch) {
if sender.isOn {
owe?.amount = (owe?.amount)! * (-1)
} else {
owe?.amount = (owe?.amount)! * (1)
}
}
}
extension NewOwedDetailViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
}
PersonDetailsTableViewController: This is where I display all details of that particular person's owe history
import UIKit
import ChameleonFramework
class PersonDetailsTableViewController: UITableViewController {
#IBOutlet weak var personDetailsTableView: UITableView!
let dateFormatter = DateFormatter()
var person: People?
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.timeStyle = .long
dateFormatter.dateStyle = .long
}
override func viewWillAppear(_ animated: Bool) {
self.personDetailsTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addNewOwe(_ sender: Any) {
performSegue(withIdentifier: "addOweDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? NewOwedDetailViewController else {
return
}
destination.person = person
}
func deleteOwe(at indexPath: IndexPath) {
guard let owe = person?.owe?[indexPath.row],
let managedContext = owe.managedObjectContext else {
return
}
managedContext.delete(owe)
do {
try managedContext.save()
personDetailsTableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
print("Could not delete owes")
personDetailsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
}
extension PersonDetailsTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return person?.owe?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = personDetailsTableView.dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
if let owe = person?.owe?[indexPath.row] {
cell.textLabel?.text = owe.name
if let amount = person?.owe?[indexPath.row] {
cell.detailTextLabel?.text = "₹ \(owe.amount)"
}
}
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteOwe(at: indexPath)
}
}
}
extension PersonDetailsTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "addOweDetails", sender: self)
}
}
Screen
PersonDetailsTableViewController
NewOwedDetailViewController

Swift 2.2, RealmSwift - Retrieval of data not working

I am using realm for my notepad app to store the array noteTitles, which is of a custom class Note. The app works fine, but when it is supposed to save, it doesn't pass through. When I restart the app, the notes are gone. I will give code to all of the files. Also, I want the user to add notes and I need the ObjectForPrimaryKey to update everytime so a new id is created for each note.
Note Class Code:
import Foundation
import RealmSwift
class Note: Object {
dynamic var title = ""
var content = ""
var id = 0
override class func primaryKey() -> String? {
print("id generated")
return "id"
}
}
ViewController(Where I write the notes) Code:
import UIKit
import RealmSwift
var note2 = Note()
var note: Note!
let realm = try! Realm()
class ViewController3: UIViewController, UITextViewDelegate {
var note: Note!
#IBOutlet var noteText: UITextView!
#IBOutlet var noteTitle: UITextField!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
noteTitle.text = note.title
noteText.text = note.content
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
note.title = noteTitle.text!
note.content = noteText.text
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewDidEndEditing(textView: UITextView) {
func noteEnded(note2: Note) {
note2.title = note.title
note2.content = note.content
note2.id = note.id
do {
try realm.write {
realm.add(noteTitles, update: true)
print("added")
}
} catch {
print("There was a problem")
}
}
print("editing ended")
}
override func viewDidLoad() {
super.viewDidLoad()
print(note2.id)
self.noteText.delegate = self
// Do any additional setup after loading the view.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
noteTitle.resignFirstResponder()
noteText.resignFirstResponder()
}
}
TableViewController(Note List) Code:
import UIKit
import RealmSwift
var noteTitles:[Note] = []
class TableViewController: UITableViewController {
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return noteTitles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = noteTitles[indexPath.row].title // error here
// Configure the cell...
return cell
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
sleep(2)
if realm.objectForPrimaryKey(Note.self, key: 0) != nil {
realm.objectForPrimaryKey(Note.self, key: 0)
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
noteTitles.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier! == "editNote" {
let noteDetailViewController = segue.destinationViewController as! ViewController3
let selectedIndexPath = tableView.indexPathForSelectedRow
noteDetailViewController.note = noteTitles[selectedIndexPath!.row]
} else if segue.identifier! == "addNote" {
let note = Note()
noteTitles.append(note)
let noteDetailViewController = segue.destinationViewController as! ViewController3
noteDetailViewController.note = note
}
}
}
Thanks in advance!
The function noteEnded should not inside the textViewDidEndEditing and it is not being called.
Try this
func noteEnded(note2: Note) {
do {
try realm.write {
realm.add(note2, update: true)
print("added")
}
} catch {
print("There was a problem")
}
}
func textViewDidEndEditing(textView: UITextView) {
note2.title = note.title
note2.content = note.content
note2.id = note.id
noteEnded(note2)
print("editing ended")
}
It is also better to have "Done" button to save the note. Easy to handle the input and save.

Cannot invoke 'append' with an argument list of type'(String)' in my firstViewController

firstViewController. This is where the problem is. In my 'for loop' it is giving me an error. I have tried to use what Xcode suggested, but it isn't working. I still consider myself a beginner with Swift. I looked at other answers when people have posted the same question and I still can't solve my problem.
import UIKit
var toDoItems:[String] = []
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tasksTable:UITableView?
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDoItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = toDoItems[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
if var storedToDoItems : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {
toDoItems = []
for var i = 0; i < storedToDoItems?.count(); ++i {
toDoItems.append(storedToDoItems[i] as! String)
}
}
tasksTable?.reloadData()
}
}
This is my secondViewController.
import UIKit
class SecondViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var toDoItem: UITextField!
#IBAction func addItemButton(sender: AnyObject) {
toDoItems.append(toDoItem.text)
let fixedToDoItems = toDoItems
NSUserDefaults.standardUserDefaults().setObject(fixedToDoItems, forKey: "todDoItems")
NSUserDefaults.standardUserDefaults().synchronize()
self.view.endEditing(true)
}
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.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
}
When you load your to-do list array from NSUserDefaults, use if let to test if it's a [String] (that is, an array of strings), and then you won't need to cast it to a String later on, which might be contributing to your error. Try replacing your viewWillAppear method with this:
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = []
for var i = 0; i < storedToDoItems.count; ++i {
toDoItems.append(storedToDoItems[i])
}
}
tasksTable?.reloadData()
}
While you're at it, there's a much nicer way to loop over the contents of an array in Swift (and many other languages):
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = []
for item in storedToDoItems {
toDoItems.append(item)
}
}
tasksTable?.reloadData()
}
In this case however, you should be able to just set your variable directly from the loaded one:
override func viewWillAppear(animated: Bool) {
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
toDoItems = storedToDoItems
}
tasksTable?.reloadData()
}

Passing data back to previous view controller after selecting table view cell

I'm having trouble passing data after selecting a table view cell to the previous view controller. I'm pretty much trying to change a label from the previous view controller after selecting a table view cell. Could anyone help me go about this? I'm trying to change the UITextField after selecting a cell.
UIViewController:
class WhoToOdds: UIViewController, sendBack,UITextFieldDelegate{
#IBOutlet var chosenContact: UITextField!
#IBOutlet var oddsTextBox: UITextView!
var friend: String?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
func sendNameToPreviousVC(selectedfriendName: String) {
friend = selectedfriendName
chosenContact.text = friend
}
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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "friendList"{
let friendViewController = (segue.destinationViewController as! friendListController)
var fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
PFUser.currentUser()?["friend_list"] = result
PFUser.currentUser()?.save()
print(result)
var resultdict = result as! NSDictionary
println("Result Dict: \(resultdict)")
friendViewController.friendArray = resultdict.objectForKey("data") as! NSArray
} }
}
}
#IBAction private func submitChallenge(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
}
TableViewController:
protocol sendBack
{
func sendNameToPreviousVC(contact: String)
}
class friendListController: UITableViewController, UITableViewDataSource, UITableViewDelegate{
var friendArray:NSArray = ["a","b","c"]
var valueDict:NSDictionary = [:]
var mDelegate:sendBack?
var selectedFriend :String?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friend", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = (friendArray[indexPath.row] as! String)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
selectedFriend = currentCell.textLabel!.text as String!
sendBackFriendList(selectedFriend!)
navigationController?.popViewControllerAnimated(true)
}
func sendBackFriendList(name: String){
self.mDelegate?.sendNameToPreviousVC(name)
}
}
Your delegate needs to be set. In your case you have to set it inside prepareForSegue method like
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "friendList"{
let friendViewController = (segue.destinationViewController as! friendListController)
friendViewController.mDelegate = self //Include this line
//rest of the code
}
}
You didn't set the delegate in your segue, so mDelegate is nil in your sendBackFriendList method

Passing data from one tableview to another tableview using segue in swift

I am really struggling to pass data from SecondViewController to ActivityFormTableViewController.
get this error: 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'MajorActivity''
Code for two classes follow:
Any help would be received with gratitude.
//
// SecondViewController.swift
// LinkByActivity
//
// Created by Jeremy Andrews on 2015/06/10.
// version update 23/06/2015
// Copyright (c) 2015 Jeremy Andrews. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
let textCellIdentifier = "TextCell"
var catRet = XnYCategories.mainCats("main")
var activityDictionary = [String : [String]]()
var key1:String!
#IBAction func ActivityMainCats(segue:UIStoryboardSegue) {
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return catRet.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = catRet[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var row = indexPath.row
let key1 = catRet[row]
println(key1)
performSegueWithIdentifier("MajorActivity", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "MajorActivity") {
var svc = segue.destinationViewController as! ActivityFormTableViewController;
svc.key2 = key1
println(key1)
}
}
}
//
// ActivityFormTableViewController.swift
// LinkByActivity
//
// Created by Jeremy Andrews on 2015/07/24.
// Copyright (c) 2015 Jeremy Andrews. All rights reserved.
//
import UIKit
class ActivityFormTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView2: UITableView!
var key2:String!
var catRet2 = XnYCategories.mainCats("Sport")
let textCellIdentifier = "TextCell2"
var activityDictionary = [String : [String]]()
override func viewDidLoad() {
super.viewDidLoad()
println(key2)
var catRet2 = XnYCategories.mainCats(key2)
println(catRet2)
tableView.delegate = self
tableView.dataSource = self
}
// MARK: UITextFieldDelegate Methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//var catRet2 = XnYCategories.mainCats(key2)
return catRet2.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = catRet2[row]
return cell
}
// MARK: UITableViewDelegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var row = indexPath.row
let activityKey = "CellNo_" + "famNam_" + key2
activityDictionary = [activityKey: ["TheForm", "l1", "etc"]]
//println(activityDictionary)
}
}
You need to create a UINavigationController in your prepareForSegue method because it appears as that's what you have on your storyboard. Then you need to create an instance of the controller that you want the navigation controller to show and assign your properties to that.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "MajorActivity") {
let activityFormNavController = segue.destinationViewController as! UINavigationController
let svc = activityFormNavController.topViewController as! ActivityFormTableViewController
svc.key2 = key1
println(key1)
}
}
Storyboard Example:
ViewController.swift
import UIKit
class ViewController: UIViewController {
var someString : 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.
}
#IBAction func fireSegueBttnTouched(sender: AnyObject) {
// set my local instance variable to some value to pass
someString = "Stack Overflow Is Great!"
performSegueWithIdentifier("next", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "next" {
// Create a UINavigationController instance first b/c that's where the segue goes
let nextNavVc = segue.destinationViewController as! UINavigationController
// Create an instance of the top view controller belonging to the above crated navigation controller
let nextVc = nextNavVc.topViewController as! SecondViewController
// Assign the instance variable from this view controller to the variable on the view controller nextVc
nextVc.passedString = someString
}
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var outputLabel: UILabel!
var passedString : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
if passedString != nil {
outputLabel.text = passedString!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Simulator Screenshots:

Resources