ios 在故事板中,如何制作用于多个控制器的自定义单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9245969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:46:47  来源:igfitidea点击:

In a storyboard, how do I make a custom cell for use with multiple controllers?

objective-ciosuitableviewstoryboard

提问by Cliff W

I'm trying to use storyboards in an app I'm working on. In the app there are Listsand Usersand each contains a collection of the other (members of a list, lists owned by a user). So, accordingly, I have ListCelland UserCellclasses. The goal is to have those be re-usable throughout the app (ie, in any of my tableview controllers).

我正在尝试在我正在开发的应用程序中使用故事板。在应用程序中有列表用户,每个都包含另一个集合(列表的成员,用户拥有的列表)。所以,相应地,我有ListCellUserCell班级。目标是让它们在整个应用程序中(即,在我的任何 tableview 控制器中)可重复使用。

That's where I'm running into a problem.

这就是我遇到问题的地方。

How do I create a custom tableview cell in the storyboard that can be re-used in any view controller?

如何在故事板中创建可以在任何视图控制器中重复使用的自定义 tableview 单元格?

Here are the specific things I've tried so far.

以下是我迄今为止尝试过的具体事情。

  • In Controller #1, added a prototype cell, set the class to my UITableViewCellsubclass, set the reuse id, added the labels and wired them to the class's outlets. In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before. When it runs, the labels never appear when the cells are shown in Controller #2. Works fine in Controller #1.

  • Designed each cell type in a different NIB and wired up to the appropriate cell class. In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class. In controllers' viewDidLoadmethods, registered those NIB files for the reuse id. When shown, cells in both controllers were empty like the prototype.

  • Kept prototypes in both controllers empty and set class and reuse id to my cell class. Constructed the cells' UI entirely in code. Cells work perfectly in all controllers.

  • 在 Controller #1 中,添加了一个原型单元,将类设置为我的UITableViewCell子类,设置重用 ID,添加标签并将它们连接到类的插座。在 Controller #2 中,添加了一个空的原型单元格,将其设置为与以前相同的类并重用 id。当它运行时,当单元格显示在控制器 #2 中时,标签永远不会出现。在控制器 #1 中工作正常。

  • 在不同的 NIB 中设计每种细胞类型并连接到适当的细胞类别。在故事板中,添加了一个空的原型单元格并设置其类并重用 id 来引用我的单元格类。在控制器的viewDidLoad方法中,为重用 ID 注册这些 NIB 文件。显示时,两个控制器中的单元格都像原型一样是空的。

  • 将两个控制器中的原型保持为空并设置类并将 id 重用于我的单元类。完全在代码中构建单元格的 UI。单元格在所有控制器中都能完美运行。

In the second case I suspect that the prototype is always overriding the NIB and if I killed the prototype cells, registering my NIB for the reuse id would work. But then I wouldn't be able to setup segues from the cells to other frames, which is really the whole point of using storyboards.

在第二种情况下,我怀疑原型总是覆盖 NIB,如果我杀死了原型单元,则将我的 NIB 注册为重用 ID 会起作用。但是我将无法设置从单元格到其他帧的转场,这才是使用故事板的真正意义所在。

At the end of the day, I want two things: wire up tableview based flows in the storyboard and define cell layouts visually rather than in code. I can't see how to get both of those so far.

归根结底,我想要两件事:在故事板中连接基于 tableview 的流,并以视觉方式而不是在代码中定义单元格布局。到目前为止,我不知道如何获得这两个。

采纳答案by BJ Homer

As I understand it, you want to:

据我了解,您想要:

  1. Design a cell in IB which can be used in multiple storyboard scenes.
  2. Configure unique storyboard segues from that cell, depending on the scene the cell is in.
  1. 在 IB 中设计一个可用于多个故事板场景的单元格。
  2. 根据单元格所在的场景,从该单元格配置独特的故事板转场。

Unfortunately, there is currently no way to do this. To understand why your previous attempts didn't work, you need to understand more about how storyboards and prototype table view cells work. (If you don't care about whythese other attempts didn't work, feel free to leave now. I've got no magical workarounds for you, other than suggesting that you file a bug.)

不幸的是,目前没有办法做到这一点。要了解为什么您之前的尝试无效,您需要更多地了解故事板和原型表视图单元格的工作原理。(如果您不关心为什么这些其他尝试不起作用,请随时离开。除了建议您提交错误之外,我没有给您任何神奇的解决方法。)

A storyboard is, in essence, not much more than a collection of .xib files. When you load up a table view controller that has some prototype cells out of a storyboard, here's what happens:

从本质上讲,故事板只不过是 .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:

    1. Look at the class of the cell, as defined in the cell's nib. Call [[CellClass alloc] initWithCoder:].
    2. 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.

  • 每个原型单元实际上都是它自己的嵌入式迷你笔尖。因此,当表视图控制器加载时,它会遍历每个原型单元格的笔尖并调用-[UITableView registerNib:forCellReuseIdentifier:].
  • 表格视图向控制器询问单元格。
  • 你可能会打电话 -[UITableView dequeueReusableCellWithIdentifier:]
  • 当您请求具有给定重用标识符的单元格时,它会检查它是否已注册笔尖。如果是,它会实例化该单元格的一个实例。这由以下步骤组成:

    1. 查看单元格的类,如单元格的笔尖中所定义。打电话[[CellClass alloc] initWithCoder:]
    2. -initWithCoder:方法遍历并添加子视图并设置在笔尖中定义的属性。(IBOutlet虽然我还没有测试过,但它可能也被连接到这里;它可能发生在-awakeFromNib
  • 您可以根据需要配置您的单元。

The important thing to note here is there is a distinction between the classof the cell and the visual appearanceof the cell. You could create two separate prototype cells of the same class, but with their subviews laid out completely differently. In fact, if you use the default UITableViewCellstyles, this is exactly what's happening. The "Default" style and the "Subtitle" style, for example, are both represented by the same UITableViewCellclass.

这里要注意的重要一点是,单元格的类别和单元格的视觉外观之间存在区别。您可以创建同一类的两个单独的原型单元格,但它们的子视图布局完全不同。事实上,如果您使用默认UITableViewCell样式,就会发生这种情况。例如,“默认”样式和“字幕”样式都由同一个UITableViewCell类表示。

This is important: The classof the cell does not have a one-to-one correlation with a particular view hierarchy. The view hierarchy is determined entirely by what's in the prototype cell that was registered with this particular controller.

这很重要:单元格的与特定的视图层次结构没有一对一的相关性。视图层次完全由注册到这个特定控制器的原型单元中的内容决定。

Note, as well, that the cell's reuse identifier was not registered in some global cell dispensary. The reuse identifier is only used within the context of a single UITableViewinstance.

另请注意,细胞的重用标识符未在某些全球细胞药房中注册。重用标识符仅在单个UITableView实例的上下文中使用。



Given this information, let's look at what happened in your above attempts.

有了这些信息,让我们看看在您的上述尝试中发生了什么。

In Controller #1, added a prototype cell, set the class to my UITableViewCell subclass, set the reuse id, added the labels and wired them to the class's outlets. In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before. When it runs, the labels never appear when the cells are shown in Controller #2. Works fine in Controller #1.

在控制器 #1 中,添加了一个原型单元,将类设置为我的 UITableViewCell 子类,设置重用 ID,添加标签并将它们连接到类的插座。在 Controller #2 中,添加了一个空的原型单元格,将其设置为与以前相同的类并重用 id。当它运行时,当单元格显示在控制器 #2 中时,标签永远不会出现。在控制器 #1 中工作正常。

This is expected. While both cells had the same class, the view hierarchy that was passed to the cell in Controller #2 was entirely devoid of subviews. So you got an empty cell, which is exactly what you put in the prototype.

这是预期的。虽然两个单元格具有相同的类,但传递给控制器​​ #2 中单元格的视图层次结构完全没有子视图。所以你得到了一个空单元格,这正是你放入原型中的内容。

Designed each cell type in a different NIB and wired up to the appropriate cell class. In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class. In controllers' viewDidLoad methods, registered those NIB files for the reuse id. When shown, cells in both controllers were empty like the prototype.

在不同的 NIB 中设计每种细胞类型并连接到适当的细胞类别。在故事板中,添加了一个空的原型单元格并设置其类并重用 id 来引用我的单元格类。在控制器的 viewDidLoad 方法中,为重用 ID 注册这些 NIB 文件。显示时,两个控制器中的单元格都像原型一样是空的。

Again, this is expected. The reuse identifier is not shared between storyboard scenes or nibs, so the fact that all of these distinct cells had the same reuse identifier was meaningless. The cell you get back from the tableview will have an appearance that matches the prototype cell in that scene of the storyboard.

再次,这是意料之中的。重用标识符在故事板场景或笔尖之间不共享,因此所有这些不同的单元格具有相同的重用标识符这一事实毫无意义。您从 tableview 返回的单元格的外观将与故事板场景中的原型单元格相匹配。

This solution was close, though. As you noted, you could just programmatically call -[UITableView registerNib:forCellReuseIdentifier:], passing the UINibcontaining 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.

不过,这个解决方案很接近。正如您所指出的,您只需以编程方式调用-[UITableView registerNib:forCellReuseIdentifier:],传递UINib包含单元格的内容,您就会返回同一个单元格。(这不是因为原型“覆盖”了笔尖;您只是没有在 tableview 中注册笔尖,所以它仍在查看嵌入在故事板中的笔尖。)不幸的是,这种方法有一个缺陷——无法将故事板 segue 连接到独立笔尖中的单元格。

Kept prototypes in both controllers empty and set class and reuse id to my cell class. Constructed the cells' UI entirely in code. Cells work perfectly in all controllers.

将两个控制器中的原型保持为空并设置类并将 id 重用于我的单元类。完全在代码中构建单元格的 UI。单元格在所有控制器中都能完美运行。

Naturally. Hopefully, this is unsurprising.

自然。希望这并不奇怪。



So, that's why it didn't work. You can design your cells in standalone nibs and use them in multiple storyboard scenes; you just can't currently hook up storyboard segues to those cells. Hopefully, though, you've learned something in the process of reading this.

所以,这就是它不起作用的原因。您可以在独立的笔尖中设计单元格并在多个故事板场景中使用它们;您目前无法将故事板 segue 连接到这些单元格。不过,希望您在阅读本文的过程中学到了一些东西。

回答by ericteubert

In spite of the great answer by BJ Homer I feel like I have a solution. As far as my testing goes, it works.

尽管 BJ Homer 给出了很好的答案,但我觉得我有一个解决方案。就我的测试而言,它有效。

Concept: Create a custom class for the xib cell. There you can wait for a touch event and perform the segue programmatically. Now all we need is a reference to the controller performing the Segue. My solution is to set it in tableView:cellForRowAtIndexPath:.

概念:为xib单元创建自定义类。在那里您可以等待触摸事件并以编程方式执行 segue。现在我们需要的是对执行 Segue 的控制器的引用。我的解决方案是将其设置为tableView:cellForRowAtIndexPath:.

Example

例子

I have a DetailedTaskCell.xibcontaining a table cell which I'd like to use in multiple table views:

我有一个DetailedTaskCell.xib包含我想在多个表格视图中使用的表格单元格:

DetailedTaskCell.xib

详细任务单元.xib

There is a custom class TaskGuessTableCellfor that cell:

TaskGuessTableCell该单元格有一个自定义类:

enter image description here

在此处输入图片说明

This is where the magic happens.

这就是魔法发生的地方。

// TaskGuessTableCell.h
#import <Foundation/Foundation.h>

@interface TaskGuessTableCell : UITableViewCell
@property (nonatomic, weak) UIViewController *controller;
@end

// TashGuessTableCell.m
#import "TaskGuessTableCell.h"

@implementation TaskGuessTableCell

@synthesize controller;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSIndexPath *path = [controller.tableView indexPathForCell:self];
    [controller.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
    [controller performSegueWithIdentifier:@"FinishedTask" sender:controller];
    [super touchesEnded:touches withEvent:event];
}

@end

I have multiple Segues but they all have the same name: "FinishedTask". If you need to be flexible here, I suggest to add another property.

我有多个 Segue,但它们都有相同的名称:"FinishedTask". 如果您需要在这里灵活,我建议添加另一个属性。

The ViewController looks like this:

视图控制器看起来像这样:

// LogbookViewController.m
#import "LogbookViewController.h"
#import "TaskGuessTableCell.h"

@implementation LogbookViewController

- (void)viewDidLoad
{
    [super viewDidLoad]

    // register custom nib
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailedTaskCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DetailedTaskCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TaskGuessTableCell *cell;

    cell = [tableView dequeueReusableCellWithIdentifier:@"DetailedTaskCell"];
    cell.controller = self; // <-- the line that matters
    // if you added the seque property to the cell class, set that one here
    // cell.segue = @"TheSegueYouNeedToTrigger";
    cell.taskTitle.text  = [entry title];
    // set other outlet values etc. ...

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"FinishedTask"])
    {
        // do what you have to do, as usual
    }

}

@end

There might be more elegant ways to achieve the same but - it works! :)

可能有更优雅的方法来实现相同的但 - 它有效!:)

回答by Odrakir

I was looking for this and I found this answerby Richard Venable. It works for me.

我正在寻找这个,我找到了 Richard Venable 的答案。这个对我有用。

iOS 5 includes a new method on UITableView: registerNib:forCellReuseIdentifier:

To use it, put a UITableViewCell in a nib. It has to be the only root object in the nib.

You can register the nib after loading your tableView, then when you call dequeueReusableCellWithIdentifier: with the cell identifier, it will pull it from the nib, just like if you had used a Storyboard prototype cell.

iOS 5 在 UITableView 上包含了一个新方法:registerNib:forCellReuseIdentifier:

要使用它,请将 UITableViewCell 放入笔尖。它必须是笔尖中唯一的根对象。

您可以在加载 tableView 后注册笔尖,然后当您使用单元格标识符调用 dequeueReusableCellWithIdentifier: 时,它将从笔尖中拉出它,就像您使用 Storyboard 原型单元格一样。

回答by Kunal Kumar

Swift 3

斯威夫特 3

BJ Homer gave an excellent explanation, It helps me understand the concept. To make a custom cell reusable in storyboard, which can be used in any TableViewController we have to mix the Storyboard and xibapproach. Suppose we have a cell named as CustomCellwhich is to be used in the TableViewControllerOneand TableViewControllerTwo. I am making it in steps.
1.File > New > Click File > Select Cocoa Touch Class > click Next > Give Name Of your class(for example CustomCell) > select Subclass as UITableVieCell > Tick the also create XIB file checkbox and press Next.
2.Customize the cell as you want and set the identifier in attribute inspector for cell, here we ll set as CellIdentifier. This identifier will be used in your ViewController to identify and reuse the Cell.
3.Now we just have to register this cellin our ViewController viewDidLoad. No need of any initialization method.
4.Now we can use this custom cell in any tableView.

BJ Homer 给出了一个很好的解释,它帮助我理解了这个概念。To make a custom cell reusable in storyboard,它可以在我们必须mix the Storyboard and xib处理的任何 TableViewController 中使用。假设我们有一个名为 as 的单元格,CustomCell它将在TableViewControllerOneand 中使用TableViewControllerTwo。我正在逐步完成。
1.文件>新建>点击文件>选择Cocoa Touch Class>点击下一步>给你的类命名(例如CustomCell)>选择子类为UITableVieCell>勾选也创建XIB文件复选框并按下一步。
2.根据需要自定义单元格并在单元格的属性检查器中设置标识符,这里我们将设置为CellIdentifier。此标识符将在您的 ViewController 中用于识别和重用 Cell。
3.现在我们只需要register this cell在我们的 ViewController 中viewDidLoad。不需要任何初始化方法。
4.现在我们可以在任何 tableView 中使用这个自定义单元格。

In TableViewControllerOne

在 TableViewControllerOne 中

let reuseIdentifier = "CellIdentifier"

override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: reuseIdentifier)
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier:reuseIdentifier, for: indexPath) as! CustomCell
    return cell!
}

回答by jrturton

BJ Homer has given an excellent explanation of what is going on.

BJ Homer 对正在发生的事情给出了很好的解释。

From a practical standpoint I'd add that, given you can't have cells as xibs AND connect segues, the best one to choose is having the cell as a xib - transitions are far easier to maintain than cell layouts and properties across multiple places, and your segues are likely to be different from your different controllers anyway. You can define the segue directly from your table view controller to the next controller, and perform it in code. .

从实际的角度来看,我要补充一点,鉴于您不能将单元格作为 xib 并连接 segues,最好的选择是将单元格作为 xib - 转换比跨多个位置的单元格布局和属性更容易维护,无论如何,您的转场很可能与您的不同控制器不同。您可以直接定义从您的表视图控制器到下一个控制器的转场,并在代码中执行它。.

A further note is that having your cell as a separate xib file prevents you being able to connect any actions etc. directly to the table view controller (I haven't worked this out, anyway - you can't define file's owner as anything meaningful). I am working around this by defining a protocol that the cell's table view controller is expected to conform to and adding the controller as a weak property, similar to a delegate, in cellForRowAtIndexPath.

还要注意的是,将您的单元格作为单独的 xib 文件会阻止您将任何操作等直接连接到表视图控制器(无论如何,我还没有解决这个问题 - 您不能将文件的所有者定义为任何有意义的东西) )。我正在通过定义一个协议来解决这个问题,单元格的表视图控制器应该符合该协议,并将控制器添加为一个弱属性,类似于一个委托,在 cellForRowAtIndexPath 中。

回答by Jo?o Nunes

I found a way to load the cell for the same VC, not tested for the segues. This could be a workaround for creating the cell in a separate nib

我找到了一种为同一个 VC 加载单元的方法,没有针对 segue 进行测试。这可能是在单独的笔尖中创建单元格的解决方法

Let's say that you have one VC and 2 tables and you want to design a cell in storyboard and use it in both tables.

假设您有一个 VC 和 2 个表,并且您想在故事板中设计一个单元格并在两个表中使用它。

(ex: a table and a search field with a UISearchController with a table for results and you want to use the same Cell in both)

(例如:一个表和一个带有 UISearchController 的搜索字段和一个结果表,并且您想在两者中使用相同的 Cell)

When the controller asks for the cell do this:

当控制器要求单元格时,请执行以下操作:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"CELL_ID";

    ContactsCell *cell = [self.YOURTABLEVIEW dequeueReusableCellWithIdentifier:identifier];
  // Ignore the "tableView" argument
}

And here you have your cell from the storyboard

在这里你有故事板中的单元格