如何在 Swift 中创建自定义 UITableViewCell class?

How do I create a custom UITableViewCell class in Swift?

我正在尝试遵循 Swift 中的以下 Using Auto Layout in UITableView for dynamic cell layouts & variable row heights 最佳答案,但 IOS 7 版本是为了减轻 IOS 8 中的一些错误。

现在,我的自定义单元格 class 是:

class PostCell: UITableViewCell {

    @IBOutlet var name: UILabel!
    @IBOutlet var timestamp: UILabel!
    @IBOutlet var postBody: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

在我的 Storyboard 中,我将自定义 class 设置为单元格的 class。我不知道我是否必须在任何地方使用我的 reuseIdentifier。我不知道如何在下一段代码中让它工作。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    var cell = PostCell()

    var post = self.posts[indexPath.row]

    cell.name.text = post.name
    cell.timestamp.text = post.timestamp
    cell.postBody.text = post.body

    cell.setNeedsUpdateConstraints()
    cell.updateConstraintsIfNeeded()

    cell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(feed.bounds), CGRectGetHeight(cell.bounds))

    cell.setNeedsLayout()
    cell.layoutIfNeeded()

    var height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height

    height += 1.0

    return height
}

我认为这会起作用,但是当我调用 cell.name.text = post.name 时,我得到了一个 EXC_BAD_INSTRUCTION。我猜这个单元格没有以某种方式正确地连接到故事板。我该如何解决这个问题?

问题是你不明白 nib 是如何工作的。您已将 PostCell 设置为在从其 nib 加载时进行配置:

class PostCell: UITableViewCell {
    @IBOutlet var name: UILabel!
}

所以这意味着 namenil - 直到从笔尖实例化此单元格,此时将连接插座。但后来你说:

var cell = PostCell()

但是那个是错误的PostCell!您没有从笔尖加载它;你只是用整块布做了一个。因此,由于没有 nib-loading,插座(正如您正确怀疑的那样)自然不会连接,因此 cell.namenil

所以解决办法是:不要整块布做一个。从笔尖加载它。