我正在尝试遵循以下 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!
}
所以这意味着 name
是 nil
- 直到从 Nib 实例化此单元格,此时 socket 将被连接。但后来你说:
var cell = PostCell()
但是 是错误的 PostCell!您没有从 Nib 加载它;你只是用整 block 布做了一个。因此,由于没有 nib 加载, socket (如您正确怀疑的那样)自然不会连接,因此 cell.name
为 nil
。
所以解决办法是:不要用整 block 布做一个。从 Nib 加载它。
关于ios - 如何在 Swift 中创建自定义 UITableViewCell 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258181/