如何解决如何将tableView标签传递给另一个viewController中的名称变量?
我正在为一个学校项目创建一个应用程序,并且我有一个tableView,其中的标签包含单元格的名称,并且我试图将标签的名称传递给第二个viewController的navTitle变量。我尝试了多种方法来实现这一目标,但是没有运气。
我尝试打印通过的标题,但是它打印输出'nil'
主视图
var names = ["Accomodation","Facilities","Things To Do","About"]
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "homeCell",for: indexPath) as? homeTableViewCell
cell?.label.text = names[indexPath.row]
return cell!
}
//Passing data
var nameChosen : String?
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath,animated: true)
nameChosen = names[indexPath.row]
performSegue(withIdentifier: "accomodationSegue",sender: self)
}
override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
let destinationVC = segue.destination as? accomodationViewController
destinationVC?.navTitle = nameChosen
}
住宿视图
var navTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
print(navTitle)
// Do any additional setup after loading the view.
}
解决方法
最简单的方法是将名称作为sender
参数传递,不需要属性nameChosen
。
在prepare(for segue
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath,animated: true)
let name = names[indexPath.row]
performSegue(withIdentifier: "accomodationSegue",sender: name)
}
override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
guard segue.identifier == "accomodationSegue" else { return }
let destinationVC = segue.destination as! accomodationViewController
destinationVC.navTitle = sender as! String
}
如果代码崩溃,则说明您犯了一个设计错误。
并且请始终使用大写字母(AccomodationViewController
)来命名类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。