将正确的信息从表视图传递到新的视图控制器时遇到问题



现在我有一个程序,可以在表格视图中显示不同的组织。选择组织后,它将显示一个屏幕,其中传递该特定组织的名称。但是,问题是,当我单击"部分 2"的"组织 1"时,我得到的结果将显示在"部分 1"的"组织 1"中。我将如何解决此问题,以便当我单击"部分 2"的"组织 2"时,它会显示正确的信息?

这是我的第一个视图控制器的代码。

import UIKit
struct Organizations {
var sectionTitle = String()
var rowTitles = [String]()
}
class SearchOrganizationsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchOrganizations: Organizations?
var selectedRow = 0
var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = organizations[indexPath.section]
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as?    OrganizationsDetailViewController {
destination.organization = selectedOrganizations
destination.selectedRow = selectedRow 
}
}

这是我第二个视图控制器的代码。

import UIKit
class OrganizationsDetailViewController: UIViewController {
@IBOutlet weak var organizationNameLabel: UILabel!
var organization: Organizations? = nil 
var selecterRow: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
setupLabel()
}
private func setupLabel() {
guard let org = self.organization else { return }
self.organizationNameLabel.text = org.rowTitles[selectedRow]
}
}

修改您的didSelectRow以解决您提到的问题:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = searching ? searchArray[indexPath.section] : organizations[indexPath.section]
selectedRow = indexPath.row
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}

最新更新