swift - 按下 UITableViewCell 时的 UIViewController

标签 swift uitableview

我正在尝试制作一个应用程序,以便在按下 UITableView 中的单元格时,它会打开一个新的 ViewController,其中包含之前在单击的初始单元格。

这是我的细胞: My Cells 这是我正在使用的数组:

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/

相关文章:

ios - 从日期数组中获取最早的日期

swift - 无法滚动到 tableView 中某个部分的一行

ios - 调整放置在 UITableView 的页眉中的 UIImage 大小

ios - 当单元格被选中时,按钮的背景颜色会改变然后恢复

ios - 防止 UITextView.typingattributes 在 Swift 中的换行符 (\n) 上应用 backgroundColor

Swift:在 AppDelegate.swift 中执行 Segue

ios - 如何在 JTCalender 中设置日期限制?

ios - 在 Swift 中收到新数据时返回新的 Cell

ios - 图像不适合自定义表格 View 单元格中的 ImageView

ios - UICollectionView - 如何设置行的背景颜色