Как получить доступ к UiLabel в пользовательской ячейке с помощью indexPath и внедрить данные пользователя в метку
Привет, я пытался исправить это в течение 4 дней, и все же не повезло, поэтому любая помощь будет оценена. Я пытаюсь создать табличное представление, где работники могут загружать свои профили, а пользователи могут просматривать, какие из них им нравятся (см. Фотографию симулятора), однако, когда я использую indexPath.row, он заполняет всю ячейку, только когда я хочу, чтобы она была заполнена. одну метку, чтобы я мог настроить разные метки с данными, которые я хочу.
Вот мой код контроллера табличного представления:
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
}
И мой собственный код ячейки таблицы просмотра
import UIKit
class MyCellTableViewCell: UITableViewCell {
@IBOutlet weak var firstName: UILabel!
@IBOutlet weak var pricePerHour: UILabel!
@IBOutlet weak var extraDetails: UILabel!
@IBOutlet var profilePic: UIImageView!
}
Если у вас есть еще вопросы о деталях, пожалуйста, задавайте:) спасибо!!
1 ответ
Я бы порекомендовал создать новую функцию, которая заполняет массив словарей.
Я не проверял это, но это должно работать как-то так. Если кто-то может проверить это или сразу увидит ошибку, пожалуйста, сообщите мне!
Там могут быть некоторые проблемы, связанные с идентификаторами пользователей. Я не слишком знаком с пожарной базой.
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
}