Unrecognized selector sent to instance when display pictures - ios

I have the following code//
// doctorsList.swift
// iLegaltwo
//
// Created by Bharath on 10/1/16.
// Copyright © 2016 Bharath. All rights reserved.
//
import UIKit
import Parse
class doctorsList: UITableViewController {
#IBOutlet var doctorsListTableView: UITableView!
var profImages = [PFFile]()
var doctorName = [String]()
var doctorRate = [NSDecimal]()
var doctorPracArea = [String]()
var doctorExp = [String]()
var refresher: UIRefreshControl!
func refresh()
{
let query = PFQuery(className: "doctors_Directory")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock(
{
(listll: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(listll!.count) names of the doctors.")
// Do something with the found objects
if let objects = listll {
for object in objects {
print(object)
self.profImages.append(object["ProfileImage"] as! PFFile)
self.doctorName.append(object["doctor_Name"] as! String)
self.doctorExp.append(object["Exp"] as! String)
self.doctorPracArea.append(object["Practice_Area"] as! String)
// print(object["doctor_Name"] as! String )
// self.doctorsname.append(object["doctor_Name"] as! String)
//self.lblName.text = object["doctor_Name"] as? String
}
self.doctorsListTableView.reloadData()
}
print(self.doctorName.count)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
self.tableView.reloadData()
self.refresher.endRefreshing()
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refrehsh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return doctorName.count
//return 6
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let doctorcell: doctorsListCell = tableView.dequeueReusableCellWithIdentifier("doctorlistproto") as! doctorsListCell
doctorcell.lblNamell.text = doctorName[indexPath.row]
doctorcell.lblExpll.text = doctorExp[indexPath.row]
doctorcell.lblPracareall.text = doctorPracArea[indexPath.row]
profImages[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if imageData != nil {
let image = UIImage(data: imageData!)
doctorcell.imagedoctor.image = image
}
else
{
print(error)
} }
//cell.textLabel?.text = doctorsname[indexPath.row]
return doctorcell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
EDIT
doctorListCell class
import UIKit
class doctorsListCell: UITableViewCell {
#IBOutlet var imagedoctor: UIImageView!
#IBOutlet var lblNamell: UILabel!
#IBOutlet var lblRatell: UILabel!
#IBOutlet var lblExpll: UILabel!
#IBOutlet var lblPracareall: UILabel!
}
No issues when I build, but not able to display profileImages, this is the error I get in the output window
2016-01-24 00:42:33.275 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ee6760
2016-01-24 00:42:33.276 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8e87670
2016-01-24 00:42:33.276 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ed3540
2016-01-24 00:42:33.277 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ed2420

-[UITableViewCellContentView setImage:]: unrecognized selector sent to instance
That's saying that you're trying to do a setImage: on a UITableViewCellContentView object (which doesn't have this method), and not on a UIImageView (imageDoctor) as you wrote it:
doctorcell.imagedoctor.image = image
So my guess, which seems to be the reason is that you linked imageDoctor (IBOutlet) to the contentView of doctorsListCell instead of the UIImageView.

Related

Retrieving firebase children and populating them in a UITableView

Trying to query firebase children and retrieve a snapshot array of their data into a tableview. Not sure if I am implementing this correctly, but I am not the getting a runtime error. However, my tableview is just white with no objects displaying. Some feedback would be helpful. Thanks.
Here is my FB JSON tree structure
Here is my User class (var userList = User)
class CDetailTableViewController: UITableViewController {
static var imageCache = NSCache<AnyObject, UIImage>()
var userList = [User]()
var ref = FIREBASE.FBDataReference().ref
var refHandle: UInt!
override func viewDidLoad() {
super.viewDidLoad()
ref = FIREBASE.FBLink().FBref
configureCell()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
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 userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CDetailTableViewCell
cell.priceLabel?.text = userList[indexPath.row].priceLabel
cell.titleLabel?.text = userList[indexPath.row].titleLabel
cell.itemPhoto?.image = userList[indexPath.row].objectImage
return cell
}
func configureCell(){
let ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
refHandle = ref.child("Enterpriser Listings").child("Sell Old Stuff - Listings").child(userID!).observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
print("get dictionary")
print(dictionary)
let user = User()
user.setValuesForKeys(dictionary)
self.userList.append(user)
// Get user value
DispatchQueue.main.async {
print("reloaded")
self.tableView.reloadData()
}
}
})
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
May be the problem is with your Firebase reference, try like this way.
ref.child("Enterpriser Listings").child("Sell Old Stuff - Listings").observe(.value, with: { (snapshot:FIRDataSnapshot) in
var users = [User]()
for child in snapshot.children {
print("\((sweet as! FIRDataSnapshot).value)")
if let dictionary = child.value as? [String : AnyObject] {
let user = User()
user.setValuesForKeys(dictionary)
users.append(user)
}
}
self.userList = users
self.tableView.reloadData()
})
Simple question. Have you delegated your tableview?
class YourController: < other >, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() { //for example this function
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}

load images made slow my tableview

I got my data from a json url, but when I want to load my images, it is very slowly !
class NewsTableViewController: UITableViewController {
var ids = [String]()
var titles = [String]()
var descriptions = [String]()
var images = [String]()
var links = [String]()
var dates = [String]()
#IBOutlet var table_news: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table_news.delegate = self
getNews()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
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 self.ids.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:NewsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "news_cell") as! NewsTableViewCell
cell.lbl_date.text = self.dates[indexPath.row]
cell.lbl_title.text = self.titles[indexPath.row]
var des = self.descriptions[indexPath.row]
if des.characters.count > 200 {
let range = des.rangeOfComposedCharacterSequences(for: des.startIndex..<des.index(des.startIndex, offsetBy: 200))
let tmpValue = des.substring(with: range).appending("...")
cell.lbl_des.text = tmpValue
}
DispatchQueue.main.async{
cell.img_news.setImageFromURl(stringImageUrl: self.images[indexPath.row])
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func getNews() {
RestApiManager.sharedInstance.getNews { (json: JSON) in
if let results = json.array {
for entry in results {
self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!)
self.descriptions.append(entry["description"].string!)
self.images.append(entry["images"].string!)
self.links.append(entry["link"].string!)
self.dates.append(entry["date"].string!)
}
DispatchQueue.main.async{
self.table_news.reloadData()
}
}
}
}
}
custom cell:
extension UIImageView{
func setImageFromURl(stringImageUrl url: String){
if let url = NSURL(string: url) {
if let data = NSData(contentsOf: url as URL) {
self.image = UIImage(data: data as Data)
}
}
}
}
class NewsTableViewCell: UITableViewCell {
#IBOutlet weak var img_news: UIImageView!
#IBOutlet weak var lbl_title: UILabel!
#IBOutlet weak var lbl_date: UILabel!
#IBOutlet weak var lbl_des: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
lbl_des.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping
lbl_des.numberOfLines = 0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I'm using an extension image view.
The problem for the slowness you are mentioning are in the UIImageView extension
extension UIImageView{
func setImageFromURl(stringImageUrl url: String){
if let url = NSURL(string: url) {
if let data = NSData(contentsOf: url as URL) {
self.image = UIImage(data: data as Data)
}
}
}
}
In the NSData(contentsOf: url as URL) you are retrieving the contents of the URL synchronously from the network, blocking the main thread. You can download the content using a NSURLSession with an asynchronous callback or using some 3rd party libraries (SDWebImage probably being the most used and battle tested).

Return number field from Parse into Tableview custom cell

I have a tableview controller with a custom Prototype Cell. The cell contains 2 labels. I am trying to return 2 values from a Parse class. One field is called Notes and is a String value. The other field is called CreditAmount and is a number value. I am having difficulty returning the number value (Credit Amount) in my tableview.
Here is code for tableview controller:
import UIKit
import Parse
import Foundation
class TableViewController: UITableViewController {
var note = [String]()
var credit = [NSInteger]()
var refresher: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
updateNotes()
self.refresher = UIRefreshControl()
self.refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refresher.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
}
func updateNotes() {
let query = PFQuery(className: "Paydown")
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]?, error: NSError?) -> Void in
self.note.removeAll(keepCapacity: true)
self.credit.removeAll(keepCapacity: true)
if let objects = objects as? [PFObject] {
for object in objects {
// var noted = object as PFObject
self.note.append(object["Notes"] as! String)
self.credit.append(object["CreditAmount"] as! NSInteger)
}
self.tableView.reloadData()
} else {
//println(error)
}
self.refresher.endRefreshing()
})
}
func refresh() {
updateNotes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return note.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
myCell.notesLabel.text = note[indexPath.row]
myCell.amountLabel.text = credit[indexPath.row]
return myCell
}
}
Here is the code for my customer cell:
import UIKit
import Parse
class cell: UITableViewCell {
#IBOutlet weak var notesLabel: UILabel!
#IBOutlet weak var amountLabel: 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
}
}
The myCell.amountLabel.text = credit[indexPath.row] causes an error: cannot assign a value of type NSInteger (aka int) to a value of type String?. How do I get the number field to work?
Update
myCell.amountLabel.text = credit[indexPath.row]
To be
myCell.amountLabel.text = "\(credit[indexPath.row])"

Type does not have a member names 'objectForKey' and use of unresolved identifiers

Using swift/parse to attempt to populate custom cell in the following table view controller. The pfquery code seems to be going fine, but when I attempt to use the the data to populate cell.something.text with what should be returned results, I receive errors indicating that type does not a have a member named 'objectForKey' and Use of unresolved identifiers. The errors are specifically all occurring under the override func tableView(tableView..cellForRowAtIndexPath....
import UIKit
class TimeLineTableViewController: UITableViewController {
var timelineData:NSMutableArray = NSMutableArray()
override init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func loadData(){
timelineData.removeAllObjects()
//let predicate = NSPredicate(format: PFuser = PFUser.current)
var findTimelineData:PFQuery = PFQuery(className: "event")
//findTimelineData.whereKey(PFUser.self, equalTo: PFUser.currentUser())
findTimelineData.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
self.timelineData.addObject(object)
println(object.objectId)
}
let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
self.timelineData = array as NSMutableArray
self.tableView.reloadData()
}
} else {
// Log details of the failure
println("Error: \(error) \(error.userInfo!)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return timelineData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TimeLineTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TimeLineTableViewCell
let event:PFObject = self.timelineData.objectAtIndex(indexPath.row) as PFObject
cell.eventLabel.alpha = 0
cell.dateLabel.alpha = 0
cell.minutesLabel.alpha = 0
cell.eventLabel.text = Category.objectForKey("content") as String
cell.minutesLabel.text = duration.objectForKey
var dataFormatter:NSDateFormatter = NSDateFormatter()
dataFormatter.dateFormat = "yyyy-MM-dd HH:mm"
cell.dateLabel.text = dataFormatter.stringFromDate(category.createdAt)
var findRecorder:PFQuery = PFUser.query()
findRecorder.whereKey("objectId", equalTo: event.objectForKey(user).objectId)
findRecorder.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
let user:PFUser = (objects as NSArray).lastObject as PFUser
UIView.animateWithDuration(0.5, animations: {
cell.eventLabel.alpha = 1
cell.dateLabel.alpha = 1
cell.minutesLabel.alpha = 1
})
}
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
Your problem is that you're using variables you didn't initialize anywhere in your code:
cell.minutesLabel.text = duration.objectForKey
^
cell.dateLabel.text = dataFormatter.stringFromDate(category.createdAt)
^
You never initialize duration or category in your code. So you can't access it. You first need to initialize it.
Also I'm not sure but it looks like that you don't import the Parse framework (maybe you do but it's not in the code you've provided)
So you will need to import it first:
import Parse

delegate modal view swift

I have tried the other methods for delegation and protocols for passing data between modal views and the parent view button they aren't working for me. This is obviously because I am implementing them wrong.
What I have is a parent view controller which has a tableviewcell which in the right detail will tell you your selection from the modal view. The modal view is another table view which allows you to select a cell, which updates the right detail and dismisses the modal view. All is working except the actual data transfer.
Thanks in advance!! :)
Here is my code for the parent view controller:
class TableViewController: UITableViewController, UITextFieldDelegate {
//Properties
var delegate: transferData?
//Outlets
#IBOutlet var productLabel: UILabel!
#IBOutlet var rightDetail: UILabel!
override func viewWillAppear(animated: Bool) {
println(delegate?.productCarrier)
println(delegate?.priceCarrier)
if delegate?.productCarrier != "" {
rightDetail.text = delegate?.productCarrier
productLabel.text = delegate?.productCarrier
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 5
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
The code for the model view controller and protocol is:
protocol transferData {
var priceCarrier: Double { get set }
var productCarrier: String { get set }
}
class ProductsDetailsViewController: UITableViewController, transferData {
//Properties
var priceCarrier = 00.00
var productCarrier = ""
//Outlets
//Actions
#IBAction func unwindToViewController(segue: UIStoryboardSegue) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
populateDefaultCategories()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return Int(Category.allObjects().count)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return (Category.allObjects()[UInt(section)] as Category).name
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return Int(objectsForSection(section).count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:ProductListCell = tableView.dequeueReusableCellWithIdentifier("productCell", forIndexPath: indexPath) as ProductListCell
let queriedProductResult = objectForProductFromSection(indexPath.section, indexPath.row)
cell.name.text = queriedProductResult.name
cell.prices.text = "$\(queriedProductResult.price)"
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow()!
let product = objectForProductFromSection(indexPath.section, indexPath.row)
let PVC: TableViewController = TableViewController()
println("didSelect")
productCarrier = product.name
priceCarrier = product.price
println(productCarrier)
println(priceCarrier)
self.dismissViewControllerAnimated(true, completion: nil)
}
I think for passing data, you should use segue like:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow()!
let product = objectForProductFromSection(indexPath.section, indexPath.row)
println("didSelect")
productCarrier = product.name
priceCarrier = product.price
println(productCarrier)
println(priceCarrier)
self.performSegueWithIdentifier("displayYourTableViewControllerSegue", sender: self)
}
and then override the prepareForSegue function:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var controller = segue.destinationViewController as TableViewController
controller.rightDetail.text = "\(self.priceCarrier)"
controller.productLabel.text = self.productCarrier
}

Resources