我正在尝试制作一个应用程序,以便在按下 UITableView
中的单元格时,它会打开一个新的 ViewController
,其中包含之前在单击的初始单元格。
let alligator:NSArray = ["American Alligator","American Crocodile","Mugger Crocodile","Saltwater Crocodile"]
这是 numberOfRowsInSection 和 cellForRowAt
:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(alligator.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell4 = tableView.dequeueReusableCell(withIdentifier: "cell4", for: indexPath) as! AlligatorViewCell
cell4.alligatorImage.image = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")
cell4.alligatorLabel.text = alligator[indexPath.row] as? String
return(cell4)
}
这是我的细节 View Controller 的导出:
@IBOutlet var detailImage:UIImageView!
@IBOutlet var detailLabel:UILabel!
这里是 didSelectRowAt
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
detailImage.image = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
detailLabel.text = alligator[indexPath.row] as? String
问题是,当我按下单元格时,出现错误,fatal error: Unexpectedly found nil while Unwrapping Optional
最佳答案
我认为您的错误正在发生,因为当您调用它时 detailImage
不存在。
据我了解,这些导出位于您的基本 View Controller 中,但它们指的是您的详细 View Controller 中的对象,这是不允许的。因此,当您尝试调用它们时,它们不会传递任何值为 nil 的东西。
因此这与初始化 UIImage 无关。
您需要在 detailViewController 类中创建 IBOutlets,然后通过您的 prepareForSegue
函数将单元格中的值传递到这些 socket 。
如果您对此有任何疑问,请告诉我。
编辑
假设你的细节 View Controller 有 detailImage 属性,那么你可以做这样的事情(在你的基础 ViewController 中)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination as! UIViewController //your detail controller
controller.detailImage = myImage //where myImage is a property of your base view controller
}
编辑
当您的单元格被点击时,您可以在 View Controller 中设置 myImage 属性,就像您之前尝试的那样。然后可以在 prepareForSegue 函数中将 myImage 设置为 detailImage。所以像这样:
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myImage = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
...
编辑
你应该像这样使用 myImage
:
var myImage: UIImage?
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myImage = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
...
关于swift - 按下 UITableViewCell 时的 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41710949/