ios - 如何在 Swift 中创建自定义 UITableViewCell 类?

标签 ios uitableview swift

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

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

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 中,我将自定义类设置为单元格的类。我不知道是否必须在任何地方使用我的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。我猜测单元格没有以某种方式正确连接到 Storyboard。我该如何解决这个问题?

最佳答案

问题是您不了解 nib 的工作原理。您已将 PostCell 设置为在从其 Nib 加载时进行配置:

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

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

var cell = PostCell()

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

所以解决办法是:不要用整 block 布做一个。从 Nib 加载它。

关于ios - 如何在 Swift 中创建自定义 UITableViewCell 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258181/

相关文章:

ios - 如何将过滤结果数组映射到原始数组(具有值语义)?

ios - UITableView:页眉和页脚 View 的绘画行为

iphone - 我应该在哪里存储图像,以便我可以使用 iTunes 文件共享它们?

ios - FacebookSDK如何重新提示用户同意?

iOS GPS 精度,我的 iPhone 4 上的 GPS 精度如何?

ios - tableview 滚动得到错误的最后一个单元格

ios - 为 tableView 完成 ReloadData 后应用程序崩溃

ios - 为什么我的 UITextView 没有显示在我的 Swift/iOS 应用程序的自定义表格单元格中?

ios - 重用类 - 未使用的 IBOutlet 是否会导致崩溃

ios - 如何让视频在我的视频选择 Controller 中播放