【发布时间】:2017-05-16 13:32:02
【问题描述】:
我正在尝试将值从一个视图控制器传递到另一个视图控制器。正如我测试的那样,这没问题并且可以使用我的代码运行。但是当我尝试获取单元格标签值时遇到问题。我尝试了在 google 和 stackoverflow 上找到的所有内容,但对此没有答案。我在代码上添加了一条注释,上面写着// I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE,以帮助您找到我卡在哪里。
我的代码:
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 ?? "")
}
}
}
【问题讨论】:
-
使用数据源,而不是单元格。另外,您使用的是
PlacesTableViewCell,而不是经典的UITableViewCell,并且您使用placeLabel作为UILabel,而不是detailTextLabel。 -
你应该只使用
places数组来获取数据,你已经在didSelect方法中有indexPath。 -
提示 #1:遵循 Scriptable 的答案... 提示 #2:不要“尝试在 google 和 stackoverflow 上找到的所有内容” -- 阅读了解你发现了什么,然后实施它。如果您不理解,复制/粘贴代码将无济于事。
-
@DonMag 是的,你是对的!
标签: ios swift uitableview uilabel didselectrowatindexpath