Using struct to create detail view controller from tableview - ios

First of all, I am a beginner! So it's a bit complicated, but basically I am trying to create a separate view controller that displays information held in a struct/string with objects. I am making a directory. I have two controllers, one for the tableView (called DirectoryTableViewController) and one for the detail view (called FacultyViewController) and then I have a swift file (called People) that has manages the String.
I am eventually going to add name, phone, email and an image to the String, but for now I am just doing the names.
My problem is that it is working and I need some pointers. Thanks!!
Here is my DirectoryTableView:
import UIKit
struct peoples {
var teacherString: String!
var image: UIImage!
}
class DirectoryTableViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var array : [People]!
override func viewDidLoad() {
super.viewDidLoad()
print(array)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("directoryCell", forIndexPath: indexPath)
let person = array[indexPath.row]
cell.textLabel!.text = person.teacherString
return cell
}
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
}
Here is my NewViewController:
import UIKit
class NewViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var phoneTextField: UITextField!
#IBOutlet weak var emailTextTield: UITextField!
var array : [People] = []
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func crateObjectButton(sender: AnyObject) {
let object = People(name: nameTextField.text! , phone: phoneTextField.text!, email: emailTextTield.text!)
array.append(object)
performSegueWithIdentifier("TeacherData", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TeacherData" {
let dvc = segue.destinationViewController as? DirectoryTableViewController
dvc!.array = array
}
}
}
Here is People.swift (model):
import Foundation
class People {
var name : String
var phone: String
var email: String
init(name: String, phone: String, email: String) {
self.name = name
self.phone = phone
self.email = email
}
}
Thanks again!

As per your question , you have to make a model
import Foundation
class People {
var name : String
var phone: String
var email: String
init(name: String, phone: String, email: String) {
self.name = name
self.phone = phone
self.email = email
}
}
and make a view controller from where you gather all these details for eg: like this
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var phoneTextField: UITextField!
#IBOutlet weak var ageTextTield: UITextField!
var array : [People] = []
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func crateObjectButton(sender: AnyObject) {
let object = People(name: nameTextField.text! , phone: phoneTextField.text!, email: ageTextTield.text!)
array.append(object)
performSegueWithIdentifier("TeacherData", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TeacherData" {
let dvc = segue.destinationViewController as? TableviewController
dvc!.array = array
}
}
}
and this segue take you to the tableviewcontroller where in viewdidLoad i am printing the array of teachers.
import UIKit
class TableviewController: UITableViewController {
var array : [People]!
override func viewDidLoad() {
super.viewDidLoad()
print(array)
}
}
and you go to the deatil view controller of a selected teacher by using this method:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
object = array![indexPath.row]
performSegueWithIdentifier("yourdetailviewcontrollersegue", sender: self)
}

Related

Cannot assign value of type 'ViewController' to type 'AddContactDelegate?'

import UIKit
struct Contact {
var fullname: String
var contactNumber: String
}
class ViewController: UITableViewController {
var contacts = [Contact]()
#IBOutlet var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func handleAdd(_ sender: Any) {
let controller = AddContacts()
controller.delegate = self
self.present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = contacts[indexPath.row].fullname
cell.detailTextLabel?.text = contacts[indexPath.row].contactNumber
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
}
import UIKit
protocol AddContactDelegate {
func addContact(contact: Contact)
}
class AddContacts: UIViewController {
var delegate: AddContactDelegate?
#IBOutlet weak var ContactTextField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func save(_ sender: Any) {
guard let fullname = nameTextField.text, nameTextField.hasText else {
print("handle error here")
return
}
guard let contactNumber = ContactTextField.text , ContactTextField.hasText else {
print("enter contact error here")
return
}
let contact = Contact(fullname: fullname, contactNumber: contactNumber)
print(contact.fullname)
print(contact.contactNumber)
delegate?.addContact(contact: contact)
}
}
in viewController: UITableViewController file it shows error like Cannot assign value of type 'ViewController' to type 'AddContactDelegate?' what should do i do to solve these error
import UIKit
struct Contact {
var fullname: String
var contactNumber: String
}
class ViewController: UITableViewController {
var contacts = [Contact]()
#IBOutlet var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func handleAdd(_ sender: Any) {
let controller = AddContacts()
controller.delegate = self
self.present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = contacts[indexPath.row].fullname
cell.detailTextLabel?.text = contacts[indexPath.row].contactNumber
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
}
// add this
extension ViewController: AddContactDelegate {
func addContact(contact: Contact) {
contacts.append(contact)
tableView.reloadData()
}
}
// thats it
import UIKit
protocol AddContactDelegate:AnyObject {
func addContact(contact: Contact)
}
class AddContacts: UIViewController {
weak var delegate: AddContactDelegate?
#IBOutlet weak var ContactTextField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func save(_ sender: Any) {
guard let fullname = nameTextField.text, nameTextField.hasText else {
print("handle error here")
return
}
guard let contactNumber = ContactTextField.text , ContactTextField.hasText else {
print("enter contact error here")
return
}
let contact = Contact(fullname: fullname, contactNumber: contactNumber)
print(contact.fullname)
print(contact.contactNumber)
delegate?.addContact(contact: contact)
}
}
You must implement the protocol inside the ViewController.
Why xcode shows you the error is:
protocol ViewDelegate: AnyObject {
func didDoSomething()
}
// Which means - reference with name delegate can store objects that conform to the protocol ViewDelegate
var delegate: ViewDelegate
If you did not conform the object you are trying to store to this reference with the desired protocol, you will not be able to store that object to that reference.
You can look at protocols like contracts, if the protocol is implemented in a specific class, the class must implement the declared methods inside the protocols.
Simply implementing this protocol to your ViewController and adding the method declared in the protocol (contract) will make you achieve what you want.
class MyViewController: ViewDelegate {
func didDoSomething() {
//TODO: Logic for this method
}
}
//Will not give compile errors
let delegate: ViewDelegate = MyViewController()
Just for additional info, you can always implement a delegate in this way
class MyViewController {
//properties
}
//MARK: - ViewDelegate implementation
extension MyViewController: ViewDelegate {
func didDoSomething() {
//TODO: logic
}
}
Hope it helps.

Manipulating from grandchild view controller - Swift Xcode

This is my first time using swift or Xcode.
I'm trying to make a simple transaction register app
The first view has a table, in which each row represents an account and it's balance.
When you click on a row, it opens up a second view, via segue, which contains a table of all transactions for that account. At the top of this view there is an 'Add Transaction' button, which opens up a third view, that has a form and an 'Add' button. When the 'Add' button is pressed, I use the .reloadData() on the table in the second view and the third view is dismissed.
But, the table, visually, does not have an additional row in it. Which is because after the 3rd view closes, the newly added transaction is no longer in the transactions array.
Am I doing something wrong? My attempt and images are below.
First view
import UIKit
class AccountsViewController: UIViewController {
#IBOutlet weak var newAccountNameUITextField: UITextField!
#IBOutlet weak var newAccountBalanceUITextField: UITextField!
#IBOutlet weak var addNewAccountUIButton: UIButton!
#IBOutlet weak var accountsUITableView: UITableView!
var selectedAccount: Account = Account(name: "", balance: "")
var accounts = [Account(name: "PNC", balance: "45.93")]
override func viewDidLoad() {
super.viewDidLoad()
accountsUITableView.delegate = self
accountsUITableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let transactionsViewController = segue.destination as? TransactionsViewController {
transactionsViewController.modalPresentationStyle = .fullScreen
transactionsViewController.account = selectedAccount
}
}
}
extension AccountsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedAccount = accounts[indexPath.row]
performSegue(withIdentifier: "trasactionsSegue", sender: self)
}
}
extension AccountsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return accounts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "account", for: indexPath) as! AccountCell
cell.selectionStyle = .none
cell.nameUILabel?.text = accounts[indexPath.row].name
cell.balanceUILabel?.text = accounts[indexPath.row].balance
return cell
}
}
Second View
import UIKit
class TransactionsViewController: UIViewController {
#IBOutlet weak var nameUILabel: UILabel!
#IBOutlet weak var TransactionsUITableView: UITableView!
#IBOutlet weak var balanceUILabel: UILabel!
var account: Account = Account(name: "", balance: "", transactions: [])
override func viewDidLoad() {
super.viewDidLoad()
TransactionsUITableView.dataSource = self
nameUILabel.text = account.name
balanceUILabel.text = account.balance
}
//Pass data to newTransactionViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let newTransactionViewController = segue.destination as? NewTransactionViewController {
newTransactionViewController.account = account
}
}
//Dismiss this view when Accounts button is pressed
#IBAction func backToAccountsTouchUpInside(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.presentingViewController?.dismiss(animated: true, completion: nil)
})
}
#IBAction func addTransactionTouchUpInside(_ sender: UIButton) {
performSegue(withIdentifier: "addTransactionSegue", sender: self)
}
#IBAction func unwindToViewControllerA(segue: UIStoryboardSegue) {
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
//At this point the newly added transaction is missing
self.TransactionsUITableView.reloadData()
}
}
}
}
extension TransactionsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return account.transactions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "transaction", for: indexPath) as! TransactionCell
cell.selectionStyle = .none
cell.descriptionUILabel.text = account.transactions[indexPath.row].description
cell.amountUILabel.text = account.transactions[indexPath.row].amount
cell.balanceUILabel.text = account.transactions[indexPath.row].balanceAfterAmount
return cell
}
}
Third View
import UIKit
class NewTransactionViewController: UIViewController {
#IBOutlet weak var clearedUISegmentedControl: UISegmentedControl!
#IBOutlet weak var depositingUISegmentedControl: UISegmentedControl!
#IBOutlet weak var descriptionUITextField: UITextField!
#IBOutlet weak var amountUITextField: UITextField!
#IBOutlet weak var addTransactionUIButton: UIButton!
var account: Account? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addTransactionTouchUpInside(_ sender: UIButton) {
let depositing = depositingUISegmentedControl.selectedSegmentIndex == 0 ? true : false
let cleared = clearedUISegmentedControl.selectedSegmentIndex == 0 ? true : false
let description = descriptionUITextField.text
let amount = amountUITextField.text
let balanceAfterAmount = operationOnCurrency(depositing: depositing, amount: amount!, balance: account!.balance)
let newTransaction = Transaction(depositing: depositing, amount: amount!, balanceAfterAmount: balanceAfterAmount, description: description!, cleared: cleared)
account?.transactions.append(newTransaction)
self.performSegue(withIdentifier: "backToTransactions", sender: self)
}
}
func operationOnCurrency (depositing: Bool, amount: String, balance: String) -> String {
//Return empty string for now
return ""
}
The problem is that you are appending a new Transaction in the Account instance that was created in your NewTransactionViewController, rather than updating the data in the instance held by the TransactionsViewController or the root data source in the AccountsViewController (assuming that is the root data source). You need to pass the updated data backwards when the add button is pressed. You can create a delegate protocol to take care of this. Using your transition from NewTransactionViewController to TransactionsViewController example, first create the protocol:
protocol NewTransactionDelegate {
func transactionAddedToAccount(account: Account)
}
Then inside of your NewTransactionViewController you will want to create a delegate property:
class NewTransactionViewController: UIViewController {
#IBOutlet weak var clearedUISegmentedControl: UISegmentedControl!
#IBOutlet weak var depositingUISegmentedControl: UISegmentedControl!
#IBOutlet weak var descriptionUITextField: UITextField!
#IBOutlet weak var amountUITextField: UITextField!
#IBOutlet weak var addTransactionUIButton: UIButton!
var account: Account? = nil
**var delegate: NewTransactionDelegate?**
override func viewDidLoad() {
super.viewDidLoad()
}
And inside of your addTransactionTouchUpInside method call the delegate method:
#IBAction func addTransactionTouchUpInside(_ sender: UIButton) {
let depositing = depositingUISegmentedControl.selectedSegmentIndex == 0 ? true : false
let cleared = clearedUISegmentedControl.selectedSegmentIndex == 0 ? true : false
let description = descriptionUITextField.text
let amount = amountUITextField.text
let balanceAfterAmount = operationOnCurrency(depositing: depositing, amount: amount!, balance: account!.balance)
let newTransaction = Transaction(depositing: depositing, amount: amount!, balanceAfterAmount: balanceAfterAmount, description: description!, cleared: cleared)
account?.transactions.append(newTransaction)
**delegate?.transactionAddedToAccount(account: account)**
self.performSegue(withIdentifier: "backToTransactions", sender: self)
}
Now back in your TransactionsViewController you will want to conform to the NewTransactionDelegate protocol and implement the required method declared in the protocol:
class TransactionsViewController: UIViewController, NewTransactionDelegate {
func transactionAddedToAccount(account: Account) {
self.account = account
tableView.reloadData()
}
Then when you perform the segue to transition from TransactionsViewController to NewTransactionViewController you will want to set the destination view controller's delegate property to self:
//Pass data to newTransactionViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let newTransactionViewController = segue.destination as? NewTransactionViewController {
**newTransactionViewController.delegate = self**
newTransactionViewController.account = account
}
}
Now when the add button is tapped the delegate method is called and passed the new instance of account, which is then passed back to the previous view controller and updated.
Note that this will only update in account instance in the TransactionsViewController and you will also need to update the data for this account at the source or it will be lost when TransactionsViewController is deallocated. Pass the new account back to AccountsViewController, save to device, update database, etc.

How to pass the data from view controller to the table view controller?

How to pass data from view controller to table view controller? and also how to store the selected data to the table view controller? but The output shows multiple row, how to make it based on the user click at the bag? and how to pass the data inside it?
! ]2
Here my 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!
//here the button to add to the table view
#IBAction func addtobag(_ sender: Any) {
let viewController = storyboard?.instantiateViewController(withIdentifier: "BagViewController") as? BagViewController
viewController?.name = self.name
viewController?.imagee = self.imagee
viewController?.price = self.price
viewController?.items = self.items
navigationController?.pushViewController(viewController!, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
labelname.text = name
labelprice.text = price
image.image = UIImage(named: imagee)
}
}
And here my Bag View Controller
import UIKit
class BagViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var totalprice: UILabel!
#IBOutlet weak var tableview: UITableView!
var items = [item]()
var name : String = ""
var price : String = ""
var imagee : String = ""
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return name.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! ShoppingTableViewCell
return cell
}
}
and here my Shopping Table View
import UIKit
class ShoppingTableViewCell: UITableViewCell {
#IBOutlet weak var dfs: UIImageView!
#IBOutlet weak var labelname: UILabel!
#IBOutlet weak var labelprice: UILabel!
#IBOutlet weak var stepperlabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func stepper(_ sender: UIStepper) {
stepperlabel.text = String(Int(sender.value))
}
}
I think your logic is kind of bad, you're instantiating a VC in code but you have a segue, I recommend you pass data through the prepare function:
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
if let vc = segue.destination as? BagViewController {
vc.name = self.name
vc.imagee = self.imagee
vc.price = self.price
vc.items = self.items
}
// Pass the selected object to the new view controller.
}
And in your addtobag IBAction you just will call the segue, I recommend you to use a String based segue extension String+PerformSegue.swift it lets you easily perform segue in a given ViewController like this:
#IBAction func addtobag(_ sender: Any) {
"nameOfTheSegue".performSegue(on: self)
// If you don't want to use String+PerformSegue.swift uncomment
// the next line and comment the last one.
// self.performSegue(withIdentifier: "nameOfTheSegue", sender: nil)
}

TableView Cell actions

I have a ViewController, with a list of data from a son file. This page run perfectly. On this page are many pub's with prices. And I want to make another scene (SecondViewController). And every time, when I push a pub from the list I want to display on another scene more information about that place. That run, but when I choose a pub the program shows the information about the first pub from the list, and when I choose another he shows the previous pub, which I choose before. And sorry my english is very bad. Please help me :D
Here is my ViewController:
import UIKit
var nev: [String] = []
var cim: [String] = []
var ar: [String] = []
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var myIndex: Int?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "pubok", withExtension: "json")
do {
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = allContacts["Pubok"] {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
nev.append(aObject["Hely neve"] as! String)
cim.append(aObject["Cím"] as! String)
ar.append(aObject["Legolcsóbb sör"] as! String)
}
}
self.tableView.reloadData()
}
catch {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nev.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.nevLabel.text = nev[indexPath.row]
cell.arLabel.text = ar[indexPath.row] + "/0.5l"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! SecondViewController
vc.myIndex = myIndex
}
}
Here is my SecondViewController:
import UIKit
class SecondViewController: UIViewController {
myIndex: Int?
#IBOutlet weak var secondnevLabel: UILabel!
#IBOutlet weak var secondcimLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
secondnevLabel.text = nev[myIndex!]
secondcimLabel.text = cim[myIndex!]
}
}
And this is the TableViewCell:
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var nevLabel: UILabel!
#IBOutlet weak var arLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Instead of having the global variable myIndex, have a local variable in the second view controller. Use prepare(for segue:) in the first view controller to assign the selected row index to that variable.
ViewController:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
// etc
}
// Remove didSelectRowAt
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let row = (self.tableView.indexPathForSelectedRow as NSIndexPath?)?.row
let vc = segue.destination as! SecondViewController
vc.myIndex = row
}
SecondViewController:
class SecondViewController: UIViewController {
var myIndex: Int?
#IBOutlet weak var secondnevLabel: UILabel!
#IBOutlet weak var secondcimLabel: UILabel!
// etc

Label to display item in array in not visible

Right now im following a tutorial. And i notice when i click a table cell and redirect to a new view, i found there is no detail for each cell.
ViewController.swift:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var itemsArray: [ToDoItem] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
let tempItem = itemsArray[indexPath.row]
cell.textLabel?.text = tempItem.itemName
return cell!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detailsegue" {
let destVC = segue.destinationViewController as! DetailViewController
let selectedIndex = tableView.indexPathForSelectedRow
destVC.myItem = itemsArray[selectedIndex!.row] as? ToDoItem
}
}
override func viewDidLoad() {
super.viewDidLoad()
let item1 = ToDoItem(name: "Eat", desc: "Eat until i am full. I prefer local food though!", place: "Food Court")
itemsArray.append(item1)
let item2 = ToDoItem(name: "Drink", desc: "Drink until i am full. I prefer local drink though!", place: "Drink Court")
itemsArray.append(item2)
let item3 = ToDoItem(name: "Jump", desc: "Jump until i am tired. I prefer local jump though!", place: "Sport Center")
itemsArray.append(item3)
// 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.
}
}
ToDoItem.swift:
import UIKit
class ToDoItem: NSObject {
var itemName: String
var itemDescription: String?
var itemPlace : String?
var completed: Bool
init(name: String, desc: String?, place:String?) {
self.itemName = name
self.itemDescription = desc
self.itemPlace = place
self.completed = false
}
}
my detailviewcontroller.swift
import UIKit
class DetailViewController: UIViewController {
var myItem: ToDoItem?
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var placeLabel: UILabel!
#IBOutlet weak var descLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = myItem?.itemName
placeLabel.text = myItem?.itemDescription
// 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.
}
*/
}
and here is my storyboard:
storyboard

Resources