我試圖將值從一個視圖控制器傳遞到另一個視圖控制器。正如我測試這是好的,並與我的代碼運行。但是當我嘗試採取細胞標記價值時,我遇到了問題。我嘗試了一切,我發現谷歌和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