TableviewCells with different contents - swift

im trying to make an App where the User can add a Cell and where he can add different Contents to the Cell like Name, Birthday and Hobbys for example.
So far so good.
But how can i show him the individual Contents of each Cell?
Do I have to add a ViewController with different labels, where i load the text saved for the specific cell, for example with NSuserdefaults/Coredata?
Or am I totally wrong?
What i have right now : in my viewController where i can add an item
#IBAction func doneButtonPressed(sender: AnyObject) {
name = txtFieldName.text!
vc.items.append(name)
vc.tableView.reloadData()
self.dismissViewControllerAnimated(false, completion:nil)
}
in my tableviewController:
var items = [String]();
override func viewDidLoad() {
super.viewDidLoad()
print(items)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("itemCell", forIndexPath: indexPath)
cell.textLabel!.text = items[indexPath.row]
return cell
}

You need to implement kinda this thing
NavigationController ->(segue) TableView or TVController ->(show item segue) TableView or TVController
Using this example we should have files for each tableview and cell
first pair(newsvc.swift newscell.swift)
second pair(newsitemvc.swift newsitemcell.swift)
So as we understand it's a MVC
We need implement some static data
Create Model file (add struct and initialize it)
struct News {
var time: String?
var title: String?
var text: String?
init(time: String?, title: String?,text: String?) {
self.time = time
self.title = title
self.text = text
}
}
in second file we create data for struct
let newsData = [ News(time: "10:00", title: "Test", text: "Some text"),
News(time: "11:00", title: "Test1", text: "Some text1")]
NewsCell.swift
class NewsCell: UITableViewCell {
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var textLabel: UILabel!
var news: News! {
didSet {
timeLabel = news.time
titleLabel = news.title
textLabel.text = news.text
}
}
}
in NewsViewController we need add "News" array and make it get data from "newsData"
var newsItems: [News] = newsData
update functions
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! NewsCell
let news = newsItems[indexPath.row] as News
cell.news = news
return cell
}
after it we should add segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if segue.identifier == "showItemSegue" {
if let destViewController = segue.destinationViewController as? NewsItemViewController {
let seguedArray = newsItems[indexPath.row] as News
destViewController.newSeguedArray = seguedArray
}
}
}

You would append the data to an array before setting it to said cell. You can pull this data based on what they clicked by using the index in the array and the index.row variable.

Related

tableview to tableview protocol delegates

I am trying to finish this app that is a form. once filled out a button later will be pushed for print. The first controller has a tableview that has page 1 page 2 page 3. page 1 opens and you fill in all info. when hit save it should take you back to first controller. then when you push print opens the tableview and loads all info.
I am struggling to use structs correctly. also struggling on the save button to the delegate to the print controller page.
my page controller code
class PagesController: UIViewController, UITableViewDelegate {
var pages = ["Page 1","Page 2","Page 3"]
#IBOutlet weak var pagesTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
pagesTableView.delegate = self
pagesTableView.dataSource = self
}
#IBAction func printBtnPressed(_ sender: Any) {
} }
extension PagesController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PagesCell")
cell?.textLabel?.text = pages[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
performSegue(withIdentifier: "ChildInfoSegue", sender: self)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90.0
}
}
Heres my form controller
protocol ChildDelegate {
func saveInfoBlock(form: ChildInfo)
}
class ChildInfoTableViewController: UITableViewController {
var formDelegate: ChildDelegate!
var firstNameText: UITextField = UITextField()
var lastNameText: UITextField = UITextField()
var middleNameText: UITextField = UITextField()
//MARK: From ChildInfo.swift STRUCT
var childInfo = [ChildInfo]()
var basicChildInfo = ["Child's First Name","Child's Middle Name","Child's Last Name"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in 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 basicChildInfo.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChildInfoCell") as! ChildInfoTableViewCell
cell.formLabel.text = basicChildInfo[indexPath.row]
return cell
}
//MARK: Segue to printController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let path = self.tableView.indexPathForSelectedRow!
let destViewController = segue.destination as! PrintPageTableViewController
}
//MARK: Cancel Button Pressed
#IBAction func cancelBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func saveBtnPressed(_ sender: Any) {
let firstname = firstNameText.text ?? ""
let middlename = middleNameText.text ?? ""
let lastname = lastNameText.text ?? ""
let formData = ChildInfo(cFirstName: firstname, cMiddleName: middlename, cLastName: lastname)
self.navigationController?.popViewController(animated: true)
formDelegate.saveInfoBlock(form: formData)
saveInfoBLock()
}
func saveInfoBLock() {
print("Saving Info")
dismiss(animated: true, completion: nil)
}
}
Heres my struct that I don't properly use
struct ChildInfo {
var childFirstName: String?
var childMiddleName: String?
var childLastName: String?
var childsMadeUpName: String = ""
init(cFirstName: String, cMiddleName: String, cLastName: String) {
self.childFirstName = cFirstName
self.childMiddleName = cMiddleName
self.childLastName = cLastName
}
}
and lastly my tableviewcell
class ChildInfoTableViewCell: UITableViewCell {
#IBOutlet weak var formText: UITextField!
#IBOutlet weak var formLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Once the delegate protocol gets passed. What would a put in the printtableviewcontroller to make the data show? I had someone help me on here, but It was all programmatically and I'm no that advanced yet.
There are several things you can do:
Use delegation. I am assuming this is what you want to achieve here.
Pass your data through Segues. ( Recommended )
To use delegation, you have to have a clear concept of how delegation works.
Here is a link to an explanation I gave someone on another site. It breaks it down, I think this may help you a bit.
https://teamtreehouse.com/community/totally-confused-with-the-example-used
For now, I think the solution to your problem is to use Segues.
When you tap on the button to take you to the ChildInfoTableViewController where you fill the information is where you want to create your "ChildInfo" object. Then when you press save, you trigger the segue and pass the "ChildInfo" object to the "PagesController".
Then from there, that same object should be pass through the segue into the print view.

How do I get text fields inside a table view to talk to each other?

Specifically for a calculator app. I want to type in the textfield in the first row and have that change text in the other rows. Really, type in any row and change the value of the other rows.
I know I should be working with ints but I was going to worry about type converting later.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
//label and text_field come from CustomTableViewCell.swift
cell.label.text = array[indexPath.row]
cell.text_field.text = array_values[indexPath.row]
return cell
}
This is inside my tableViewController class and thats the func that generates the rows from the arrays.
Im after something like when you type in a text field, hit a button, and it updates some label, but where theres no button and text fields update other text fields as the user types. Inside a table view.
Heres the rest of the code.
import UIKit
class TableViewController: UITableViewController {
#IBOutlet var table_view: UITableView!
var array = [String]()
var array_values = [String]()
override func viewDidLoad() {
super.viewDidLoad()
array = ["1", "2", "3", "4", "5"]
array_values = ["", "", "", "", ""]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
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("cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.label.text = array[indexPath.row]
cell.text_field.text = array_values[indexPath.row]
return cell
}
}
import UIKit
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var text_field: UITextField!
#IBOutlet weak var label: 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
}
}

textLabel?.text displays only "Label" but not the actual data passed from previous Table View

What I want to achieve: I want to click on one of the rows in my first view controller to move to another table view controller.
The problem: When I click the row, the view only shows "Label" and not the data I intend to pass through. Granted the application does not crash and the white background with the "Label" heading shows up, the data is still not being shown on the 2nd view controller.
What I have done so ffar: I have used a Struct: PageTwoItems to define the data I want to send to the 2nd View Controller.
import Foundation
import UIKit
The code for the second view controller is as follows:
class PageTwoTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var PageTwo = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PageTwo.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let Cell = self.tableView.dequeueReusableCellWithIdentifier("secondcell", forIndexPath: indexPath) as UITableViewCell
Cell.textLabel?.text = PageTwo[indexPath.row]
return Cell
}
}
The code for the first view controller is as follows:
#IBOutlet weak var tableView: UITableView!
let names = ["Cleaning", "Plumbing","Electrical", "Craftswork", "Automotive"]
let desc = ["Get your spotless home or office space", "Drains, Pipes, Faucets and more", "Lighting, Fans, AC's and more", "Installation, Assembly and more", "Tow Truck Hire, Tyre Replacement and more"]
let images = [UIImage(named:"pug"),UIImage(named:"pug2"),UIImage(named:"pug3"),UIImage(named:"pug4"),UIImage(named:"pug5")]
var PageTwo = [PageTwoItems]()
override func viewDidLoad() {
PageTwo = [PageTwoItems(nametwo:["Home Cleaning", "Office Cleaning", "Moving In/Out Cleaning"], summarytwo:["Let your home sparkle","Office space cleaning right at your fingertips","New Home or Old Home? We've got you covered"],phototwo:["","",""]),
PageTwoItems(nametwo:["Drains, Pipes & Faucets", "Showers and Bath Tubs", "Toilet and Wash Basin", "Water Heater"], summarytwo:["Fix Your Broken Pipes, Clogged Drains and Leaky Faucets","Showers and Bath Tubs working just right"," ", " "],phototwo:["","",""]),
PageTwoItems(nametwo:["Lighting Fixtures", "Air Conditioners & Fans", "Generators"], summarytwo:["..","..",".."],phototwo:["","",""]),
PageTwoItems(nametwo:["Furniture Assembly/Installation", "Interior Painting", "Doors, Windows & Curtains"], summarytwo:["..","...","..."],phototwo:["","",""]),
PageTwoItems(nametwo:["Tow Truck Hire", "Tyre/Vulcanizer Help", "Auto-Consultant"], summarytwo:["...","...","..."],phototwo:["","",""])]
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("newcell", forIndexPath:indexPath) as!CustomCell
cell.photo.image = images[indexPath.row]
cell.summary.text = desc[indexPath.row]
cell.name.text = names[indexPath.row]
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
let DestViewController = segue.destinationViewController as! PageTwoTableViewController
var PageTwoArrayTwo : PageTwoItems
PageTwoArrayTwo = PageTwo[indexPath.row]
DestViewController.PageTwo = PageTwoArrayTwo.nametwo
DestViewController.PageTwo = PageTwoArrayTwo.summarytwo
DestViewController.PageTwo = PageTwoArrayTwo.phototwo
}
}
The struct for the Page Two Items:
struct PageTwoItems {
var nametwo : [String]
var summarytwo : [String]
var phototwo : [String]
}
I think your data isn't organized correctly. What I think you are looking for is something like this:
Cleaning
Home cleaning
Office cleaning
Etc
Plumbing
Drains, Pipes & Faucets
Showers and Bath Tubs
Etc
Electrical
Lighting Fixtures
Air Conditioners & Fans
Generators
This is how I would create data structures to support this.
// This represents a single row on the detail screen
struct PageTwoItem {
var name : String
var summary : String
var photo : String
}
// this represents a single row on the main screen
struct PageData {
var name: String // goes into the table on main screen
var subitems: [PageTwoItem] // send this to the detail
}
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
// Make an array of PageData
var objects = [PageData]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
}
func setupData() {
objects = [
PageData(name: "Cleaning", subitems: [
PageTwoItem(name: "Cleaning 1", summary: "", photo: ""),
PageTwoItem(name: "Cleaning 2", summary: "", photo: ""),
PageTwoItem(name: "Cleaning 3", summary: "", photo: ""),
PageTwoItem(name: "Cleaning 4", summary: "", photo: "")
] ),
PageData(name: "Plumbing", subitems: [] ),
PageData(name: "Electrical", subitems: [] ),
PageData(name: "Craftswork", subitems: [] ),
PageData(name: "Automotive", subitems: [] ),
]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print(segue.identifier)
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = segue.destinationViewController as! DetailViewController
// tell the detail controller what we want her to show
controller.detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object.name
return cell
}
}
In the detail controller :-
import UIKit
class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
// here is where we put the data we want to show
var detailItem: PageData?
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let detailItem = detailItem {
print("count = \(detailItem.subitems.count)")
return detailItem.subitems.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DetailCell", forIndexPath: indexPath)
if let object = detailItem?.subitems[indexPath.row] {
cell.textLabel!.text = object.name
}
return cell
}
}
I think the segue you use is directly connected to tableview cell to your second view controller.
You should connect your segue between your 2 controllers and set an identifier to the attributes inspector like showSecondControllerSegue and use this method :
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier(identifier: "showSecondControllerSegue", sender: self)
}
Edit :-
Your code should be :
For the second view controller :
class PageTwoTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var pageTwo = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pageTwo.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let Cell = self.tableView.dequeueReusableCellWithIdentifier("secondcell", forIndexPath: indexPath) as UITableViewCell
Cell.textLabel?.text = pageTwo[indexPath.row]
return Cell
}
}
For the first view controller :
#IBOutlet weak var tableView: UITableView!
let names = ["Cleaning", "Plumbing","Electrical", "Craftswork", "Automotive"]
let desc = ["Get your spotless home or office space", "Drains, Pipes, Faucets and more", "Lighting, Fans, AC's and more", "Installation, Assembly and more", "Tow Truck Hire, Tyre Replacement and more"]
let images = [UIImage(named:"pug"),UIImage(named:"pug2"),UIImage(named:"pug3"),UIImage(named:"pug4"),UIImage(named:"pug5")]
var pageTwo = [PageTwoItems]()
override func viewDidLoad() {
super.viewDidLoad()
pageTwo = [PageTwoItems(nametwo:["Home Cleaning", "Office Cleaning", "Moving In/Out Cleaning"], summarytwo:["Let your home sparkle","Office space cleaning right at your fingertips","New Home or Old Home? We've got you covered"],phototwo:["","",""]),
PageTwoItems(nametwo:["Drains, Pipes & Faucets", "Showers and Bath Tubs", "Toilet and Wash Basin", "Water Heater"], summarytwo:["Fix Your Broken Pipes, Clogged Drains and Leaky Faucets","Showers and Bath Tubs working just right"," ", " "],phototwo:["","",""]),
PageTwoItems(nametwo:["Lighting Fixtures", "Air Conditioners & Fans", "Generators"], summarytwo:["..","..",".."],phototwo:["","",""]),
PageTwoItems(nametwo:["Furniture Assembly/Installation", "Interior Painting", "Doors, Windows & Curtains"], summarytwo:["..","...","..."],phototwo:["","",""]),
PageTwoItems(nametwo:["Tow Truck Hire", "Tyre/Vulcanizer Help", "Auto-Consultant"], summarytwo:["...","...","..."],phototwo:["","",""])]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("newcell", forIndexPath:indexPath) as!CustomCell
cell.photo.image = images[indexPath.row]
cell.summary.text = desc[indexPath.row]
cell.name.text = names[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier(identifier: "showSecondControllerSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
let DestViewController = segue.destinationViewController as! PageTwoTableViewController
var pageTwoArrayTwo : PageTwoItems
pageTwoArrayTwo = PageTwo[indexPath.row]
DestViewController.pageTwo = pageTwoArrayTwo.nametwo
DestViewController.pageTwo = pageTwoArrayTwo.summarytwo
DestViewController.pageTwo = pageTwoArrayTwo.phototwo
}

Swift UITableView get Selected table item

I intent to connect two UITableView in one ViewController with two different classes with different data and then get the item selected but i can't make it work
AppController.swift
class AppController: UIViewController {
#IBOutlet weak var projects_TableView: UITableView!
#IBOutlet weak var hours_TableView: UITableView!
var projects_DataSource: TableViewProjects?
var hours_DataSource: TableViewHours?
override func viewDidLoad() {
super.viewDidLoad()
projects_DataSource = TableViewProjects()
hours_DataSource = TableViewHours()
projects_TableView.dataSource = projects_DataSource
hours_TableView.dataSource = hours_DataSource
println("Table Sources Success")
}
func TableProjectsSelected() {
println("Selected Project Table")
self.performSegueWithIdentifier("projectTable", sender: AnyObject?())
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "projectTable" {
//do stuff
println("projectTable ID")
}
}
and TableViewProjects.swift
var items: [String] = ["Project 1", "Project 2", "Project 3"]
override init() {
super.init()
}
//TABLE FUNCTIONS
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "projectcell")
cell.textLabel!.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Select From Class")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appController: AppController = storyboard.instantiateViewControllerWithIdentifier("SelectProjectAndHour") as! AppController
appController.TableProjectsSelected()
}
I can't get a response from item selected from TableViewProjects.swift
Maybe you should add these codes below:
projects_TableView.delegate = projects_DataSource
hours_TableView.delegate = hours_DataSource

Changing Labels in DetailVC from tableView

I’m trying to make changes to a label in a DetailViewController, depending on which row we click:
That is how my test App looks
For example, if we click Ferrari I want to display:
“Wow , it's a beautiful red Ferrari of the year… blablabla..”
But if you click another instead:
“I’m the label of the…. car”
Essentially, one description for each car.
How do I change the label?
My code :
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var valueToPass : String!
//crear un color
let medOrange: UIColor = UIColor(red: 0.973, green: 0.388, blue: 0.173, alpha: 1)
var vehicleData : [String] = ["Ferrari 458" , "Lamborghini Murcielago" , "Bugatti Veyron", "Mercedes Benz Biome"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var nib = UINib(nibName: "TableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
//Propiedades de la tableView
self.tableView.backgroundColor = medOrange
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vehicleData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TableViewCell
cell.lblCarName.text = vehicleData[indexPath.row]
cell.imgCar.image = UIImage(named: vehicleData[indexPath.row])
cell.backgroundColor = medOrange
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Has seleccionado la celda #\(indexPath.row)!")
//Obtener la label de la celda
let indexPath = tableView.indexPathForSelectedRow()
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
valueToPass = currentCell.textLabel?.text
performSegueWithIdentifier("DetailView", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "DetailView") {
var vc = segue.destinationViewController as DetailViewController
vc.passedValue = valueToPass
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
import UIKit
class DetailViewController: UIViewController {
var passedValue : String!
#IBOutlet weak var lblDetail: UILabel!
#IBOutlet weak var imgDetail: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
From what I can see you did all well and the only part missing in your code is setting passedValue to label in your DetailViewController so just add the following in viewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
lblDetail.text = passedValue
}
EDITED:
To pass description to DetaliViewContorller you have to store it somehow first and the best way to do it is by declaring a struct that holds both name and description
struct Vehicle {
var vehicleName : String
var vehicleDescription : String
}
Then your vehicleData array should contain objects of type Vehicle
var vehicleData : [Vehice] = [Vehicle(vehicleName : "Ferrari 458",vehicleDescription : "Ferrari desc" ), //Add all vehicles like this...]
And finally passedValue must be initialized like this
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
valueToPass = vehicleData[indexPath.row].vehicleDescription
performSegueWithIdentifier("DetailView", sender: self)
}
its Simple do the following steps:
add one more array with the details text in the details view controller.
when user click on the row you need to get the index.row and pass it to your details view controller.
retrive data from your number 1 step array using index path.
add it to your Lable.
and must set your Lable.text in the ViewDidLoad method.