我在表格视图中有一个集合视图(Netflix App Style)。我遵循了本教程:https://www.thorntech.com/2016/01/scrolling-in-two-directions-like-netflix-part-2-making-api-calls/
现在我想实现一个函数,每当我点击一个集合视图时,它会将员工的名字传递给下一个视图控制器。 这是我的代码:
import UIKit
class CategoryRow: UITableViewCell, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var jobpost:JobPosition?
var employee: Employee?
var myname = ""
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return jobpost!.Employees.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! EmployeeCell
cell.employeephoto.image = UIImage(named: "spanner")
cell.employeename.text = jobpost?.Employees[indexPath.row].name
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let myname = jobpost?.Employees[indexPath.row].name
//print(myname)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let EmployeeDetailPage = segue.destination as? EmployeeDetailViewController
EmployeeDetailPage?.employeename = myname
print(myname)
}
现在问题是,整个PrepareForSegue函数实际上并没有运行。该应用程序正常运行没有任何错误,但数据没有通过? (即印刷品(myname)实际上没有印刷任何东西)。
我错过了什么吗?非常感谢。
答案 0 :(得分:2)
在CategoryRow中创建一个全局变量
var myname: String!
更改didSelectItemAt func,如下所示
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
myname = jobpost?.Employees[indexPath.row].name
performSegue(withIdentifier: "EmployeeDetailViewController", sender: myname)
}
在EmployeeDetailViewController中创建一个变量
var employeename: String!
为您的segue指定一个标识符。在这里我给出“EmployeeDetailViewController” 然后更改prepareForSegue func,如下所示
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EmployeeDetailViewController" {
if let EmployeeDetailVC = segue.destination as? EmployeeDetailViewController {
EmployeeDetailVC.employeename = myname
}
}
}
答案 1 :(得分:1)
看起来您的问题是您在myname
方法中设置了一个名为collectionView(_:didSelectItemAt:)
的本地let常量,而不是设置类的myname
属性。
let myname = jobpost?.Employees[indexPath.row].name
应该是:
myname = jobpost?.Employees[indexPath.row].name