swift - 带有选项的自定义 UITableViewCell

标签 swift uitableview

我正在为我的 tableView 创建自定义单元格。我制作了一个 swift 文件:

import Foundation
import UIKit

class CellForPost: UITableViewCell {
    @IBOutlet weak var postLikes: UILabel!
    @IBOutlet weak var postText: UILabel!
    @IBOutlet weak var postDate: UILabel!
    @IBOutlet weak var postPhoto: UIImageView!
}

并在委托(delegate)方法中实现:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost
    cell.postPhoto.image = UIImage.init(data: (posts[indexPath.item].postPhoto)! as NSData)
    cell.postText.text = posts[indexPath.item].postText
    cell.postLikes.text = String(posts[indexPath.item].postLikes!)
    cell.postDate.text = timestampToDate(posts[indexPath.item].postDate!)
    return cell
}

当帖子内容完整时,一切都很好,但是当例如没有照片(在 post 结构中是可选的)时,它会崩溃并显示消息

fatal error: unexpectedly found nil while unwrapping an Optional value

我理解这个消息,所以我尝试制作

@IBOutlet weak var postPhoto: UIImageView?

就像一个可选值,但它不起作用,因为编译器要我在插入到单元格之前展开值。 附言如果可以给出一个关于在 imageView 为 nil 时完全删除并调整行高以适合其大小的简短建议。

最佳答案

你不需要修改你的 outlets 声明,你需要在 cellForRowAtIndexPath 方法中检查 nil(并设置 nil 作为值)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost

    var image: UIImage? = nil
    if let imageData = posts[indexPath.item].postPhoto {
        image = UIImage.init(data: imageData)
    }
    cell.postPhoto.image = image

    cell.postText.text = posts[indexPath.item].postText

    var postLikes: String? = nil
    if let likesData = posts[indexPath.item].postLikes {
        postLikes = String(likesData)
    }
    cell.postLikes.text = postLikes

    var postDate: String? = nil
    if let dateData = posts[indexPath.item].postDate {
        postDate = timestampToDate(dateData)
    }
    cell.postDate.text = postDate

    return cell
}

关于swift - 带有选项的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223877/

相关文章:

ios - SpriteKit Swift 节点数问题

ios - 如何对从 WebService 接收到的数据执行搜索操作?

ios - 如何在 prepareForSegue 方法中访问对象数组中选定对象的不同属性或特性

iphone - 清除 tableView 单元格缓存(或删除条目)

ios - Xcode 11.4 - 归档项目 - 段错误 11

swift - 快速从 firebase 数据库中读取子值

objective-c - 使用 Swift 中的 block 调用 Objective-C 方法

ios - map 框 : How to change MGLFillStyleLayer "fill-outline-width"

ios - 从 Tableview 自定义单元翻转到 UIViewController

iphone - 如何使 uitableviewcell 不可选择