Not able to display values in another viewcontroller from TableView in Swift - ios

I want to display the details of one one table row onto another viewController. But it shows an error saying ' fatal error: unexpectedly found nil while unwrapping an Optional value'
The code for my VC is as follows:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate,UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var nameForUser: UITextField!
#IBOutlet var loginButton: UIButton!
#IBOutlet var tableView: UITableView!
let allEvents = Events.allEvents
var nextScreenRow: Events!
override func viewDidLoad() {
super.viewDidLoad()
//nameForUser.text! = "Please Enter Name Here"
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.text = ""
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allEvents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventsCell")!
let event = self.allEvents[indexPath.row]
cell.textLabel?.text = event.eventName
cell.imageView?.image = UIImage(named: event.imageName)
cell.detailTextLabel?.text = event.entryType
//cell.textLabel?.text = allEvents[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
nextScreenRow = allEvents[indexPath.row]
performSegueWithIdentifier("tryToConnect", sender:self)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.allEvents.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let sec = collectionView.dequeueReusableCellWithReuseIdentifier("eventsSec", forIndexPath: indexPath) as! GridCollectionViewCell
let event = self.allEvents[indexPath.row]
sec.imageView.image = UIImage(named: event.imageName)
sec.caption.text = event.entryType
return sec
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("tryToConnect2", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "successfulLogin"){
segue.destinationViewController as! TabController
//let userName = nameForUser.text
//controller.userName = userName
}
else if (segue.identifier == "tryToConnect"){
let dest = segue.destinationViewController as! DetailedEventViewController
dest.deatiledEvent.text = nextScreenRow.eventName
dest.eventType.text = nextScreenRow.entryType
dest.imageView.image = UIImage(named: nextScreenRow.imageName)
}
}
#IBAction func loginButtonWhenPressed(sender: UIButton) {
let userName = nameForUser.text
if userName == "" {
let nextController = UIAlertController()
nextController.title = "Error!"
nextController.message = "Please enter a name"
let okAction = UIAlertAction(title: "okay", style: UIAlertActionStyle.Default) {
action in self.dismissViewControllerAnimated(true, completion: nil)
}
nextController.addAction(okAction)
self.presentViewController(nextController, animated: true, completion: nil)
}
}
}
When I run this, it shows the error. I have also assigned the delegates for the table view. The code for 'DetailedEventVC' is:
import UIKit
class DetailedEventViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var deatiledEvent: UILabel!
#IBOutlet weak var eventType: UILabel!
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.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Why does it show that the values are nil?
Help would be greatly appreciated.
Thanks in advance.
The 'EventsDetails.swift' file which has the details of events are a structure. Is there anything wrong in the way I'm calling the values?
import Foundation
import UIKit
struct Events {
let eventName: String
let entryType: String
let imageName: String
static let EventKey = "NameKey"
static let EntryTypeKey = "EntryType"
static let ImageNameKey = "ImageNameKey"
init(dictionary:[String : String]) {
self.eventName = dictionary[Events.EventKey]!
self.entryType = dictionary[Events.EntryTypeKey]!
self.imageName = dictionary[Events.ImageNameKey]!
}
}
extension Events {
static var allEvents: [Events] {
var eventsArray = [Events]()
for d in Events.localEventsData(){
eventsArray.append(Events(dictionary: d))
}
return eventsArray
}
static func localEventsData()-> [[String: String]] {
return [
[Events.EventKey:"Metallica Concert in Palace Grounds", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"Metallica"],
[Events.EventKey:"Saree Exhibition in Malleswaram Grounds", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"SareeExhibition"],
[Events.EventKey:"Wine tasting event in Links Brewery", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"WineTasting"],
[Events.EventKey:"Startups Meet in Kanteerava Stadium", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"StartupMeet"],
[Events.EventKey:"Summer Noon Party in Kumara Park", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"SummerNoonParty"],
[Events.EventKey:"Rock and Roll nights in Sarjapur Road", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"RockNRollNight"],
[Events.EventKey:"Barbecue Fridays in Whitefield", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"BBQFriday"],
[Events.EventKey:"Summer workshop in Indiranagar", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"SummerWorkshop"],
[Events.EventKey:"Impressions & Expressions in MG Road", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"ImpressionAndExpression"],
[Events.EventKey:"Italian carnival in Electronic City", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"ItalianCarnival"]
]
}
}

Create properties in your destination viewController and use them like below
import UIKit
class DetailedEventViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var deatiledEvent: UILabel!
#IBOutlet weak var eventType: UILabel!
var myImage = UIImage?
var eventDetails = ""
var typeOfEvent = ""
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = myImage
deatiledEvent.text = eventDetails
eventType.text = typeOfEvent
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and then in your first viewController you can access them like
let dest = segue.destinationViewController as! DetailedEventViewController
dest.eventDetails = nextScreenRow.eventName
dest.typeOfEvent = nextScreenRow.entryType
dest.myImage = UIImage(named: nextScreenRow.imageName)

Related

How to segue back to filled-in version of TableViewController (Swift)?

I am building a room-booking app for iOS in Xcode 9.3.
Here is the basic layout:
First TableViewController(TVC1): starts empty. Pressing '+' pops up the
Second TableViewController(TVC2) with many fields to fill in.
Once the 'Done' button on TVC2 is pressed I get back to TVC1 which now has a cell (Subtitle style) containing the details inserted.
I would now like to tap on said cell and get back to TVC2 to either check or modify the data.
I have created the segue but upon tapping I get the same version of TVC2 that I get when pressing '+', not the filled in one.
What am I doing wrong?
This is the code relative to TVC1 that I need to edit:
import UIKit
class RegistrationTableViewController: UITableViewController {
var registrations: [Registration] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return registrations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RegistrationCell", for: indexPath)
let registration = registrations[indexPath.row]
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
cell.textLabel?.text = registration.firstName + " " + registration.lastName
cell.detailTextLabel?.text = dateFormatter.string(from: registration.checkInDate) + " - " + registration.roomType.name
return cell
}
#IBAction func unwindFromAddRegistration(unwindSegue: UIStoryboardSegue) {
guard let addRegistrationTableViewController = unwindSegue.source as? AddRegistrationTableViewController,
let registration = addRegistrationTableViewController.registration else { return }
registrations.append(registration)
tableView.reloadData()
}
// MARK: Challenge.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewReservationDetails" {
}
}
And here is the code for (TVC2) so that you have more or less all the app available.
import UIKit
class AddRegistrationTableViewController: UITableViewController, SelectRoomTypeTableViewControllerDelegate {
// MARK: Properties
let checkInDatePickerCellIndexPath = IndexPath(row: 1, section: 1)
let checkOutDatePickerCellIndexPath = IndexPath(row: 3, section: 1)
var isCheckInDatePickerShown: Bool = false {
didSet {
checkInDatePicker.isHidden = !isCheckInDatePickerShown
}
}
var isCheckOutDatePickerShown: Bool = false {
didSet {
checkOutDatePicker.isHidden = !isCheckOutDatePickerShown
}
}
var roomType: RoomType?
var registration: Registration? {
guard let roomType = roomType else { return nil }
let firstName = firstNameTextField.text ?? ""
let lastName = lastNameTextField.text ?? ""
let email = emailTextField.text ?? ""
let checkInDate = checkInDatePicker.date
let checkOutDate = checkOutDatePicker.date
let numberOfAdults = Int(numberOfAdultsStepper.value)
let numberOfChildren = Int(numberOfChildrenStepper.value)
let hasWifi = wifiSwitch.isOn
return Registration(firstName: firstName, lastName: lastName, emailAddress: email, checkInDate: checkInDate, checkOutDate: checkOutDate, numberOfAdults: numberOfAdults, numberOfChildren: numberOfChildren, roomType: roomType, wifi: hasWifi)
}
var selectedItem: Registration?
// MARK: Outlets
#IBOutlet weak var firstNameTextField: UITextField!
#IBOutlet weak var lastNameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var checkInDateLabel: UILabel!
#IBOutlet weak var checkInDatePicker: UIDatePicker!
#IBOutlet weak var checkOutDateLabel: UILabel!
#IBOutlet weak var checkOutDatePicker: UIDatePicker!
#IBOutlet weak var numberOfAdultsLabel: UILabel!
#IBOutlet weak var numberOfAdultsStepper: UIStepper!
#IBOutlet weak var numberOfChildrenLabel: UILabel!
#IBOutlet weak var numberOfChildrenStepper: UIStepper!
#IBOutlet weak var roomTypeLabel: UILabel!
#IBOutlet weak var wifiSwitch: UISwitch!
// MARK: Actions
#IBAction func datePickerValueChanged(_ sender: UIDatePicker) {
updateDateViews()
}
#IBAction func stepperValueChanged(_ sender: UIStepper) {
updateNumberOfGuests()
}
#IBAction func wifiSwitchChanged(_ sender: UISwitch) {
// implemented later
}
#IBAction func cancelButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
// MARK: Methods
func updateDateViews() {
checkOutDatePicker.minimumDate = checkInDatePicker.date.addingTimeInterval(86400)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
checkInDateLabel.text = dateFormatter.string(from: checkInDatePicker.date)
checkOutDateLabel.text = dateFormatter.string(from: checkOutDatePicker.date)
}
func updateNumberOfGuests() {
numberOfAdultsLabel.text = "\(Int(numberOfAdultsStepper.value))"
numberOfChildrenLabel.text = "\(Int(numberOfChildrenStepper.value))"
}
func updateRoomType() {
if let roomType = roomType {
roomTypeLabel.text = roomType.name
} else {
roomTypeLabel.text = "Not Set"
}
}
func didSelect(roomType: RoomType) {
self.roomType = roomType
updateRoomType()
}
override func viewDidLoad() {
super.viewDidLoad()
let midnightToday = Calendar.current.startOfDay(for: Date())
checkInDatePicker.minimumDate = midnightToday
checkInDatePicker.date = midnightToday
updateDateViews()
updateNumberOfGuests()
updateRoomType()
}
// MARK: TableView Data
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch (indexPath.section, indexPath.row) {
case (checkInDatePickerCellIndexPath.section, checkInDatePickerCellIndexPath.row):
if isCheckInDatePickerShown {
return 216.0
} else {
return 0.0
}
case (checkOutDatePickerCellIndexPath.section, checkOutDatePickerCellIndexPath.row):
if isCheckOutDatePickerShown {
return 216.0
} else {
return 0.0
}
default:
return 44.0
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch (indexPath.section, indexPath.row) {
case (checkInDatePickerCellIndexPath.section, checkInDatePickerCellIndexPath.row - 1):
if isCheckInDatePickerShown {
isCheckInDatePickerShown = false
} else if isCheckOutDatePickerShown {
isCheckOutDatePickerShown = false
isCheckInDatePickerShown = true
} else {
isCheckInDatePickerShown = true
}
tableView.beginUpdates()
tableView.endUpdates()
case (checkOutDatePickerCellIndexPath.section, checkOutDatePickerCellIndexPath.row - 1):
if isCheckOutDatePickerShown {
isCheckOutDatePickerShown = false
} else if isCheckInDatePickerShown {
isCheckInDatePickerShown = false
isCheckOutDatePickerShown = true
} else {
isCheckOutDatePickerShown = true
}
tableView.beginUpdates()
tableView.endUpdates()
default:
break
}
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SelectRoomType" {
let destinationViewController = segue.destination as? SelectRoomTypeTableViewController
destinationViewController?.delegate = self
destinationViewController?.roomType = roomType
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
The challenge to this tutorial says to start from here and:
"Update the RegistrationTableViewController(TVC1) with a segue that allows the user to select and view the details of a registration in the AddRegistrationTableViewController(TVC2).
Hope this helps to provide the right solution.
Create a property let say selectedItem in TVC2 screen.
var selectedItem: Registration?
Modify prepare for cell ...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewReservationDetails" {
let sourceCell = sender as! UITableViewCell
if let indexPath = tableView.indexPath(for: sourceCell) {
if let dest = segue.destination as? <#Destination view controller#> {
dest.selectedItem = registrations[indexPath.row]
}
}
}
}
And finally in your destination view controller (having TVC2) you need to check selectedItem and assign value in viewDidLoad: or wherever.
override func viewDidLoad() {
super.viewDidLoad()
if let item = selectedItem {
//here set value as you want to views
}
}
Use this code in tableView(_:didSelectRowAt:):
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "ViewReservationDetails", sender: indexPath)
}
Then, in TVC1’s prepare(for:sender:) you pass the selected registrations element plus a completion handler to TVC2, like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewReservationDetails" {
if let destination = segue.destination as? AddRegistrationTableViewController, let indexPath = sender as? IndexPath {
destination.registration = registrations[indexPath.row]
destination.completionHandler = { (registration) in
self.registrations.append(registration)
self.tableView.reloadData()
}
}
}
}
In TVC2, you declare a property completionHandler like this:
var completionHandler: ((Registration) -> Void)?
and you call this handler in viewWillDisappear:
completionHandler?(newRegistration)
with newRegistration being the newly created element to be added to the Registration array. This way, you won’t need an unwind segue.

Showing optional value as 'nil' while changing the viewController from UITableView

I'm trying to display details from a table row onto another viewController, there are three entities which I want to display on the second VC. Two UILabel and one UIImageView. While in the first VC I'm able to view, when in the second VC, it says 'Optional("")', And don't know how to unwrap it.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate,UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var nameForUser: UITextField!
#IBOutlet var loginButton: UIButton!
#IBOutlet var tableView: UITableView!
let allEvents = Events.allEvents
var nextScreenRow: Events!
override func viewDidLoad() {
super.viewDidLoad()
//nameForUser.text! = "Please Enter Name Here"
// Do any additional setup after loading the view, typically from a nib.
//let userName = nameForUser.text
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.text = ""
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allEvents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventsCell")!
let event = self.allEvents[indexPath.row]
//print(" row \(indexPath.row)")
cell.textLabel?.text = event.eventName
cell.imageView?.image = UIImage(named: event.imageName)
cell.detailTextLabel?.text = event.entryType
//cell.textLabel?.text = allEvents[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
nextScreenRow = allEvents[indexPath.row]
let view : DetailedEventViewController = self.storyboard?.instantiateViewControllerWithIdentifier("trytry") as! DetailedEventViewController
self.navigationController?.pushViewController(view, animated: true)
print("Selected section \(indexPath.section), row \(indexPath.row)")
print(nextScreenRow.eventName)
view.eventDetails = nextScreenRow.eventName
print(view.eventDetails)
view.typeOfEvent = nextScreenRow.entryType
view.myImage = UIImage(named: nextScreenRow.imageName)
//even the 'print' is used, it is displaying here, but not in the next VC
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.allEvents.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let sec = collectionView.dequeueReusableCellWithReuseIdentifier("eventsSec", forIndexPath: indexPath) as! GridCollectionViewCell
let event = self.allEvents[indexPath.row]
sec.imageView.image = UIImage(named: event.imageName)
sec.caption.text = event.entryType
return sec
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("tryToConnect2", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "successfulLogin"){
segue.destinationViewController as! TabController
//let userName = nameForUser.text
//controller.userName = userName
}
}
#IBAction func loginButtonWhenPressed(sender: UIButton) {
let userName = nameForUser.text
if userName == "" {
let nextController = UIAlertController()
nextController.title = "Error!"
nextController.message = "Please enter a name"
let okAction = UIAlertAction(title: "okay", style: UIAlertActionStyle.Default) {
action in self.dismissViewControllerAnimated(true, completion: nil)
}
nextController.addAction(okAction)
self.presentViewController(nextController, animated: true, completion: nil)
}
}
}
And here is my second VC:
import UIKit
class DetailedEventViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var deatiledEvent: UILabel!
#IBOutlet weak var eventType: UILabel!
var eventDetails = ""
var typeOfEvent = ""
var myImage: UIImage?
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.
}
#IBAction func viewTheElemnts(sender: AnyObject) {
deatiledEvent.text = eventDetails
print(deatiledEvent.text)
eventType.text = typeOfEvent
imageView.image = myImage
}
}
Help would be appreciated greatly. Thank you.
You are creating an instance of DetailedEventViewController in the didSelectRowAtIndexPath and setting the value there. But actually you are moving to DetailedEventViewController using segue. So you should add those values in the prepareForSegue: method.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier == "trytry")
{
let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell)
nextScreenRow = allEvents[selectedIndex.row]
let view = segue.destinationViewController as! DetailedEventViewController
view.eventDetails = nextScreenRow.eventName
view.typeOfEvent = nextScreenRow.entryType
view.myImage = UIImage(named: nextScreenRow.imageName)
}
}
Unwrap your eventName like this :
view.eventDetails = nextScreenRow.eventName! as String
print(view.eventDetails) view.typeOfEvent = nextScreenRow.entryType
view.myImage = UIImage(named: nextScreenRow.imageName)
self.navigationController?.pushViewController(view, animated: true

Pass core data from selected table cell to new view controller

I'm trying to pass data (title, ingredients, steps, image) from the selected table cell to a new view controller. But I don't know how to do that. I got lots of errors, so now I'm starting again. Can anyone help me? I'm new to coding. Thanks:-) My code:
VIEWCONTROLLER.SWIFT
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var recipes = [Recipe]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
fetchAndSetResults()
tableView.reloadData()
}
func fetchAndSetResults(){
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Recipe")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.recipes = results as! [Recipe]
} catch let err as NSError {
print(err.debugDescription)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("RecipeCell") as? RecipeCell {
let recipe = recipes[indexPath.row]
cell.configureCell(recipe)
return cell
} else {
return RecipeCell()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "RecipeDetail") {
//I WANT TO PASS THE DATA FROM THE TABLE CELL TO THE NEW VIEW CONTROLLER (RECIPEDETAILVC)
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
context.deleteObject(recipes[indexPath.row])
app.saveContext()
recipes.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
}
CREATERECIPE.SWIFT
class CreateRecipeVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var recipeTitle: UITextField!
#IBOutlet weak var recipeIngredients: UITextField!
#IBOutlet weak var recipeSteps: UITextField!
#IBOutlet weak var recipeImage: UIImageView!
#IBOutlet weak var addRecipeBtn: UIButton!
var imagePicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
recipeImage.layer.cornerRadius = 5.0
recipeImage.clipsToBounds = true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
recipeImage.image = image
}
#IBAction func addImage(sender: AnyObject!) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func createRecipe(sender: AnyObject!) {
if let title = recipeTitle.text where title != "" {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Recipe", inManagedObjectContext: context)!
let recipe = Recipe(entity: entity, insertIntoManagedObjectContext: context)
recipe.title = title
recipe.ingredients = recipeIngredients.text
recipe.steps = recipeSteps.text
recipe.setRecipeImage(recipeImage.image!)
context.insertObject(recipe)
do {
try context.save()
} catch {
print("Could not save recipe")
}
self.navigationController?.popViewControllerAnimated(true)
}
}
}
RECIPEDETAILVC.SWIFT
import UIKit
import CoreData
class RecipeDetailVC: UIViewController {
#IBOutlet weak var recipeImage: UIImageView!
#IBOutlet weak var recipeTitle: UILabel!
#IBOutlet weak var recipeIngredients: UILabel!
#IBOutlet weak var recipeSteps: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//I WANT TO DISPLAY THE CORE DATA INFORMATION FROM THE TABLE CELL I SELECTED.
}
}
RECIPECELL.SWIFT
class RecipeCell: UITableViewCell {
#IBOutlet weak var recipeTitle: UILabel!
#IBOutlet weak var recipeImage: UIImageView!
func configureCell(recipe: Recipe) {
recipeTitle.text = recipe.title
recipeImage.image = recipe.getRecipeImage()
}
}
You need to track which item the person clicked.
var mySelection: Int?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
mySelection = indexPath.row
}
Then, use that when doing the segue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "RecipeDetail") {
//I WANT TO PASS THE DATA FROM THE TABLE CELL TO THE NEW VIEW CONTROLLER (RECIPEDETAILVC)
let recipeDetailControler = segue.destinationViewController as! RecipeDetailViewController
if let mySelection = mySelection {
let recipe = recipes[mySelection]
// add this function to your
recipeDetailControler.configureRecipeData(recipe)
}
}
}
Add this function to RecipeDetailViewController:
func configureRecipeData(recipe: Recipe) {
// IMPLEMENT ME
}

Swift: Send data from a UITableView to UIViewController

I have a list of Cities in a TableView and want to pass the data from the cell in TableView to a UIViewController. Now when I pass the data I also want to pass the Latitude and Longitude of those Cities to the UIViewController. Here is the TableViewController code.
class MasterTableViewController: UITableViewController
{
let fruits = ["London", "Melbourne", "Singapore", "Brazil", "Germany", "Monza", "Dallas", "Auckland", "Brussels", "Shanghai", "Sepang", "Barcelona"]
override func awakeFromNib() {
super.awakeFromNib()
}
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.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let fruit = fruits[indexPath.row]
(segue.destinationViewController as! ViewController).detailItem = fruit
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0){
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let fruit = fruits[indexPath.row]
cell.textLabel!.text = fruit
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
I can pass City but how would you pass the latitude of the longitude of the cities to the UIViewController. Here is the code for the UIViewController.
class ViewController: UIViewController {
#IBOutlet weak var currentTemperatureLabel: UILabel?
#IBOutlet weak var currentHumidityLabel: UILabel?
#IBOutlet weak var currentPrecipitationLabel: UILabel?
#IBOutlet weak var currentWeatherIcon: UIImageView?
#IBOutlet weak var currentWeatherSummary: UILabel?
#IBOutlet weak var refreshButton: UIButton?
#IBOutlet weak var activityIndicator: UIActivityIndicatorView?
#IBOutlet weak var detailDescriptionLabel: UILabel?
// Location coordinates
let coordinate: (lat: Double, lon: Double) = (37.8267,-122.423)
// TODO: Enter your API key here
private let forecastAPIKey = ""
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
retrieveWeatherForecast()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveWeatherForecast() {
let forecastService = ForecastService(APIKey: forecastAPIKey)
forecastService.getForecast(coordinate.lat, lon: coordinate.lon) {
(let currently) in
if let currentWeather = currently {
dispatch_async(dispatch_get_main_queue()) {
if let temperature = currentWeather.temperature {
self.currentTemperatureLabel?.text = "\(temperature)º"
}
if let humidity = currentWeather.humidity {
self.currentHumidityLabel?.text = "\(humidity)%"
}
if let precipitation = currentWeather.precipProbability {
self.currentPrecipitationLabel?.text = "\(precipitation)%"
}
if let icon = currentWeather.icon {
self.currentWeatherIcon?.image = icon
}
if let summary = currentWeather.summary {
self.currentWeatherSummary?.text = summary
}
self.toggleRefreshAnimation(false)
}
}
}
}
#IBAction func refreshWeather() {
toggleRefreshAnimation(true)
retrieveWeatherForecast()
}
func toggleRefreshAnimation(on: Bool) {
refreshButton?.hidden = on
if on {
activityIndicator?.startAnimating()
} else {
activityIndicator?.stopAnimating()
}
}
}
Add a property for the location to ViewController.
You can then pass the city's location in MasterTableViewController prepareForSegue, similar to how you're passing the city (detailItem) now.
Update:
To pass another parameter, you would add it to your ViewController
var coordinateItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
and then pass it in prepareForSegue
(segue.destinationViewController as! ViewController).coordinateItem = location
Update 2:
Yes, you can initialize an array of coordinates, and pass a latitude and longitude coordinate.
var locations : [[Double]] = [[51.50722, -0.12750], [-37.8136, 144.9631], ...]
In this case, your coordinateItem would be a [Double].
You can access the two doubles by coordinateItem[0] and coordinateItem[1]
The general concept is the same, regardless of whether you're passing an array or a String.

SWIFT: When i create a secondViewController, how to access to variables from original ViewController

When I go to my secondViewController using
let secondViewController:SecondViewController = SecondViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
I know I can send varibles to SECOND ONE using secondViewController.theNum = num, but while secondViewController is presented how to send varibles bar to the original ViewController.
Thing is I would like to start viewdidload() on original ViewController after this part of code is finished
self.dismissViewControllerAnimated(true, completion:nil)
Here are the full classes for two Views from a project where I pass data to a detail view and use a protocol/delegate method to return data to the first view:
View 1:
import UIKit
class Contacts: UITableViewController, dataUpdated {
//Declaring contact structure
struct contactInfo {
var name: String
var phoneNumber: String
}
var listOfContacts: [contactInfo] = []
var Duration = 100
//Sample contacts
var firstContact = contactInfo(name: "John Coffey" , phoneNumber: "(111) 111-1111")
var secondContact = contactInfo(name: "Cathy Kane" , phoneNumber: "(222) 222-2222")
//TableView delegates
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOfContacts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("contact", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = listOfContacts[indexPath.row].name
cell.detailTextLabel?.text = listOfContacts[indexPath.row].phoneNumber
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
listOfContacts.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
//ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
listOfContacts.append(firstContact)
listOfContacts.append(secondContact)
}
//Passing details to detail VC
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ToDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let theSelectedRow = listOfContacts[indexPath!.row]
let theDestination = (segue.destinationViewController as ContactDetails)
theDestination.contactName = theSelectedRow.name
theDestination.contactPhone = theSelectedRow.phoneNumber
} else if segue.identifier == "ToInput" {
(segue.destinationViewController as ContactInput).delegate = self
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let fromContact = listOfContacts[sourceIndexPath.row]
listOfContacts.removeAtIndex(sourceIndexPath.row)
listOfContacts.insert(fromContact, atIndex: destinationIndexPath.row)
}
//Delegate method to update the array with new contact
func didUpdateContact(senderClass: AnyObject, aName: String, aPhoneNumber: String) {
var newContact = contactInfo(name: aName, phoneNumber: aPhoneNumber)
listOfContacts.append(newContact)
println(listOfContacts)
self.tableView.reloadData()
}
}
View2:
import UIKit
protocol dataUpdated:NSObjectProtocol {
func didUpdateContact(senderClass: AnyObject, aName: String, aPhoneNumber: String)
}
class ContactInput: UIViewController, UITextFieldDelegate {
//Properties
var name = ""
var phoneNumber = ""
var delegate: dataUpdated?
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var phoneField: UITextField!
//Textfield delegates
func textFieldShouldReturn(textField: UITextField!) -> Bool {
if textField.tag == 1 {
self.name = textField.text
}
else {
self.phoneNumber = textField.text
}
textField.resignFirstResponder()
return true
}
//Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.nameField.delegate = self
self.phoneField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if name != "" && phoneNumber != "" {
self.delegate!.didUpdateContact(self, aName: self.name, aPhoneNumber: self.phoneNumber)
}
}
}

Resources