我将选定单元格的标签文本传递给另一个视图控制器但是每次第一次选择时它都会返回nil。之后我回去再次选择,我将获得之前选择的单元格文本。为什么?
var jobDateValueB:String!
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobTime.count //JSON Data from server
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
let unixTimestamp = Double(jobTime[indexPath.row])
let unixTimestamp2 = Double(jobEndTime[indexPath.row])
let date1 = Date(timeIntervalSince1970: unixTimestamp)
let date2 = Date(timeIntervalSince1970: unixTimestamp2)
dateFormatter.dateFormat = "h:mm a"
let strDate = dateFormatter.string(from: date1)
let endDate = dateFormatter.string(from: date2)
cell.textLabel?.text = "\(strDate) - \(endDate)"
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEdit"{
let destinationB = segue.destination as? EditTimeTableVC
destinationB?.passedDataB = jobDateValueB
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "showEdit", sender: self)
let indexPath = self.tableView.indexPathForSelectedRow;
let currentCell = self.tableView.cellForRow(at: indexPath!) as UITableViewCell!;
jobDateValueB = currentCell?.textLabel!.text!
}
EditTimeTableVC
var passedDataB: String!
override func viewDidLoad() {
super.viewDidLoad()
print(passedDataB)
}
答案 0 :(得分:0)
在didSelectRowAt
方法中,您首先调用self.performSegue
,然后设置jobDateValueB
。尝试将self.performSegue
调用移至该函数的结尾。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow;
let currentCell = self.tableView.cellForRow(at: indexPath!) as UITableViewCell!;
jobDateValueB = currentCell?.textLabel!.text!
self.performSegue(withIdentifier: "showEdit", sender: self)
}
这可以解决您的问题,但不是推荐的方法。不是将选定的文本值分配给类变量,而是将其作为发送方传递。像这样。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow;
let currentCell = self.tableView.cellForRow(at: indexPath!) as UITableViewCell!;
if let value = currentCell?.textLabel?.text? {
self.performSegue(withIdentifier: "showEdit", sender: value)
}
}
您可以使用prepare
方法。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEdit"{
let destinationB = segue.destination as? EditTimeTableVC
if let selectedText = sender as? String {
destinationB?.passedDataB = selectedText
}
}
}