我试图将值从一个视图控制器传递到另一个视图控制器。正如我测试这是好的,并与我的代码运行。但是当我尝试采取细胞标记价值时,我遇到了问题。我尝试了一切,我发现谷歌和stackoverflow,但没有答案。我在代码中添加了一条评论,其中说明// I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE
可帮助您找到卡住的位置。无法从UITableViewCell获取标签值
我的代码:
import UIKit
class PlacesTableViewController: UITableViewController {
@IBOutlet weak var placesTableView: UITableView!
var places = [Places]()
var valueToPass:String!
let cellIdentifier = "PlacesTableViewCell"
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Table view cells are reused and should be dequeued using a cell identifier.
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell else {
fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
}
let place = places[indexPath.row]
cell.placeLabel.text = place.name
cell.ratingControl.rating = place.rating
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print("You selected cell #\(indexPath.item)!")
let indexPath = placesTableView.indexPathForSelectedRow
// I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE
let currentCell = placesTableView.cellForRow(at: indexPath!)! as UITableViewCell
print(currentCell.detailTextLabel?.text ?? "Failed to use Cell Label")
valueToPass = currentCell.detailTextLabel?.text ?? "Failed to use Cell Label"
performSegue(withIdentifier: "ShowCommentsTableViewController", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ShowCommentsTableViewController") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! CommentsTableViewController
// will be stored in passedValue on the CommentsTableViewController
viewController.passedValue = valueToPass
//print (viewController.passedValue ?? "")
}
}
}
使用dataSource,而不是单元格。此外,您正在使用'PlacesTableViewCell',而不是传统的'UITableViewCell',并且'placeLabel'为'UILabel',而不是'detailTextLabel'。 – Larme
您应该只使用'places'数组来获取数据,您已经在didSelect方法中使用了indexPath。 – Aks
提示#1:遵循Scriptable的答案......提示#2:不要*“尝试你在google和stackoverflow上找到的所有内容”* - **阅读并理解你找到的内容,然后实现它。如果你不理解它,那么在复制/粘贴的代码中拍掌不会让你到任何地方。 – DonMag