1

ios simulator

Hi there, i have been trying to fix this for 4 days and still no luck so any help would be appreciated. I am trying to create a table view where workers can upload their profiles and users can scroll through to see which ones they like (see simulator photo) however when i use indexPath.row it fills out the whole cell when i only want it to fill out one label so i can configure the different labels with the data i want.

Here is my Table view controller code:

import UIKit
import FirebaseDatabase
import FirebaseStorage

struct Worker {
    var name: String!
    var price: String!
}

class SelectATaskerTableViewController: UITableViewController {

var ref: DatabaseReference!
var myList:[String] = []

@IBOutlet var myTableView: UITableView!

var handle: DatabaseHandle!
var storageHandle: StorageHandle!
var storageRef: StorageReference!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = 111

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    myTableView.delegate = self
    myTableView.dataSource = self
    ref = Database.database().reference()
    storageRef = Storage.storage().reference()
    handle = ref.child("WorkerProfile").child("Name").observe(.childAdded, with: { (snapshot) in
        if let item = snapshot.value as? String {
            self.myList.append(item)
            self.myTableView.reloadData()
        }
    })
}

@IBAction func reset(_ sender: Any) {
    Database.database().reference().child("WorkerProfile").removeValue()
}

// 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 myList.count
}

var nameText: String!
var pricePerHourText: String!
var extraDetailsText: String!
var profilePicImage: UIImage!

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell:MyCellTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellTableViewCell

   cell.firstName.text = myList[indexPath.row]
   cell.pricePerHour.text = myList[indexPath.row]

  // cell.extraDetails.text = extraDetailsText
  // cell.profilePic.image = profilePicImage
  // Configure the cell...

    return cell
}

And my custom table view cell code

import UIKit

class MyCellTableViewCell: UITableViewCell {

    @IBOutlet weak var firstName: UILabel!
    @IBOutlet weak var pricePerHour: UILabel!
    @IBOutlet weak var extraDetails: UILabel!
    @IBOutlet var profilePic: UIImageView!
  }

If you have any more questions about the details then please ask :) thank you!!

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • Did you set class to your custom cell in storyboards? – Captain Alina Aug 20 '18 at 11:46
  • yep the code works fine but i don't know what index path to use to access a specific label and not a whole row – Will Annetts Aug 20 '18 at 11:48
  • What are you trying to do? indexPath.row returns an integer. So you'll always get `myList` at that specific index. You're setting both labels to that value. I think you don't want to do that. But it's exactly what you told your program to do. Is there another list with prices? – Akaino Aug 20 '18 at 11:52
  • yes i don't want to do that. the list contains both the name and prices i think. for example i want to do index path.firstname so i can set the name to the top label and then indexPath.price so i can set the middle label to the price but it don't think you can do that, do you have any ideas how to do this?? thanks! – Will Annetts Aug 20 '18 at 11:58
  • As far as I can see you're adding "name" only. `handle = ref.child("WorkerProfile").child("Name").observe...`. You'll either a) want to make sure you get another array with "PricePerHour" which is being filled too (not recommended) or b) don't work with arrays of Strings here. Check `Dictionary` and play with it a little. I'll be much more convenient here to work with an array of Dictionaries I think. – Akaino Aug 20 '18 at 12:02
  • yes because if i add a second handle then it adds an extra cell each time :( oh okay i will try that, would it be a [string: string] dictionary then and please could you tell me how i would configure that?? – Will Annetts Aug 20 '18 at 12:08

1 Answers1

0

I'd recommend creating a new function which populates an array of dictionaries.

I haven't tested this but it should work somehow like this. If anyone is able to test this or sees an error right away, please tell me!

There might be some issue regarding userIDs. I'm not too familiar with firebase.

var myList:[[String:String]] = [] // Array of dictionaries now

@IBOutlet var myTableView: UITableView!
var handle: DatabaseHandle!
var storageHandle: StorageHandle!
var storageRef: StorageReference!

override func viewDidLoad() {  
    super.viewDidLoad()
    tableView.rowHeight = 111
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func viewWillAppear(_ animated: Bool) {
    myTableView.delegate = self
    myTableView.dataSource = self
    ref = Database.database().reference()
    storageRef = Storage.storage().reference()
    handle = ref.child("WorkerProfile").observe(.childAdded, with: { (snapshot) in
        if let item = snapshot.value as? NSDictionary {
            let itemToAppend = ["name": snapshot["Name"] as? String ?? "",
                                "pricePerHour": snapshot["PricePerHour"] as? String ?? ""
                               ]
            self.myList.append(itemToAppend)
            self.myTableView.reloadData()
        }
    })
}



@IBAction func reset(_ sender: Any) {
    Database.database().reference().child("WorkerProfile").removeValue()
}

// 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 myList.count
}

var nameText: String!
var pricePerHourText: String!
var extraDetailsText: String!
var profilePicImage: UIImage!

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:MyCellTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellTableViewCell
    cell.firstName.text = myList[indexPath.row]["name"]
    cell.pricePerHour.text = myList[indexPath.row]["pricePerHour"]
    // Configure the cell...
    return cell
}
Akaino
  • 1,025
  • 6
  • 23
  • hi akaino! I've been trying this for the last half an hour but unfortunately it doesn't work quite right :( the list is returning empty strings for name and price per hour and its also returning 3 cells in the simulator instead of one. any ideas?? – Will Annetts Aug 20 '18 at 12:59