我的理解是,你想:
在IB中设计一个可以在多个故事板场景中使用的单元格。
根据单元格所在的场景,从该单元格配置唯一的故事板segue。
不幸的是,目前还没有办法做到这一点。要理解为什么以前的尝试没有成功,您需要更多地了解故事板和原型表视图单元格是如何工作的。(如果你不关心为什么这些尝试没有成功,现在可以离开了。我没有什么神奇的解决办法,除了建议你提交一个bug。)
从本质上讲,故事板只不过是.xib文件的集合。当你从故事板中加载一个有一些原型单元格的表格视图控制器时,会发生这样的事情:
Each prototype cell is actually its own embedded mini-nib. So when the table view controller is loading up, it runs through each of the prototype cell's nibs and calls -[UITableView registerNib:forCellReuseIdentifier:].
The table view asks the controller for the cells.
You probably call -[UITableView dequeueReusableCellWithIdentifier:]
When you request a cell with a given reuse identifier, it checks whether it has a nib registered. If it does, it instantiates an instance of that cell. This is composed of the following steps:
Look at the class of the cell, as defined in the cell's nib. Call [[CellClass alloc] initWithCoder:].
The -initWithCoder: method goes through and adds subviews and sets properties that were defined in the nib. (IBOutlets probably get hooked up here as well, though I haven't tested that; it may happen in -awakeFromNib)
You configure your cell however you want.
这里需要注意的重要一点是,单元格的类和单元格的可视外观之间存在区别。您可以创建两个相同类的独立原型单元格,但是它们的子视图布局完全不同。事实上,如果你使用默认的UITableViewCell样式,这就是发生的事情。例如,“Default”样式和“Subtitle”样式都由同一个UITableViewCell类表示。
这一点很重要:单元格的类与特定的视图层次结构没有一对一的相关性。视图层次结构完全由注册到这个特定控制器的原型单元格中的内容决定。
还要注意,单元的重用标识符没有在某个全局单元药房中注册。重用标识符只在单个UITableView实例的上下文中使用。
有了这些信息,让我们看看在上述尝试中发生了什么。
在控制器#1中,添加一个原型单元格,将类设置为my
UITableViewCell子类,设置重用id,添加标签并连接
他们到班级的出口。在控制器#2中,添加了一个空
原型单元格,将其设置为与之前相同的类和重用id。当
它运行时,当单元格显示时,标签从未出现
控制器# 2。在控制器#1中工作良好。
这是意料之中的。虽然两个单元格具有相同的类,但传递给控制器#2中的单元格的视图层次结构完全没有子视图。你得到了一个空单元格,这正是你在原型中所放的。
在不同的NIB中设计每种单元类型,并连接到
适当的单元格类。在故事板中,添加一个空的原型单元格
并设置它的类和重用id来引用我的单元格类。在
控制器的viewDidLoad方法,注册了那些NIB文件
重用id。控件中的单元格显示为空
原型。
这也是意料之中的。重用标识符在故事板场景或nib之间不共享,因此所有这些不同的单元具有相同的重用标识符是没有意义的。从tableview返回的单元格将具有与故事板场景中的原型单元格相匹配的外观。
This solution was close, though. As you noted, you could just programmatically call -[UITableView registerNib:forCellReuseIdentifier:], passing the UINib containing the cell, and you'd get back that same cell. (This isn't because the prototype was "overriding" the nib; you simply hadn't registered the nib with the tableview, so it was still looking at the nib embedded in the storyboard.) Unfortunately, there's a flaw with this approach — there's no way to hook up storyboard segues to a cell in a standalone nib.
保持两个控制器中的原型为空,并设置类和重用id
我的手机班。完全用代码构建单元格的UI。细胞
工作在所有控制器完美。
自然。希望这并不令人意外。
所以,这就是为什么它不起作用。你可以在独立的nibs中设计单元格,并在多个故事板场景中使用它们;你目前不能将故事板segue连接到那些单元格。不过,希望你在阅读这篇文章的过程中学到了一些东西。