如何在 UITableViewCell 中使用预定义视图 (nib)?

How to use a predefined view (nib) in a UITableViewCell?

我的列表由带有图像和一些文本字段的卡片视图组成,所有这些都具有复杂的布局。这张卡片将在详细视图中重复使用,因此将它包含在 UITableViewCell 布局中然后调用 UITableView.registerNib() 似乎对我不起作用。我想知道最干净的方法来重用我在 NIB 文件中创建的视图作为列表项和详细信息屏幕的一部分,同时在 NIB 中保留尽可能多的视图逻辑,例如约束和样式-文件。

I'd like to know the cleanest way to reuse the view I created in the NIB-file as both a list item and a part of my detail screen

做你已经在做的事情:使用只包含一个视图的 nib(.xib 文件),即设计的 UITableViewCell,并使用 table 视图 - 正是您所说的 "doesn't seem to work for you"。 确实有效。所以现在所有 table 行都包含此 table 视图单元格的副本。

但是有窍门。当你想在别处显示视图时,手动加载笔尖,拉出视图(UITableViewCell),拉出它的contentView,并将它作为子视图添加到你的接口。

// substitute correct name of xib file here
let arr = UINib(nibName: "MyTableViewCell", bundle: nil).instantiateWithOwner(
    nil, options: nil)
let tvc = arr[0] as! UITableViewCell
let v = tvc.contentView // now it's a normal view! customize as needed
v.frame.origin = CGPointMake(100,100) // or whatever
self.view.addSubview(v) // and plop it into the interface! voilà!