简体   繁体   English

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

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

I'm trying to use storyboards in an app I'm working on.我正在尝试在我正在开发的应用程序中使用故事板。 In the app there are Lists and Users and each contains a collection of the other (members of a list, lists owned by a user).在应用程序中有列表用户,每个都包含另一个集合(列表的成员,用户拥有的列表)。 So, accordingly, I have ListCell and UserCell classes.因此,相应地,我有ListCellUserCell类。 The goal is to have those be re-usable throughout the app (ie, in any of my tableview controllers).目标是让它们在整个应用程序中(即,在我的任何 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 UITableViewCell subclass, set the reuse id, added the labels and wired them to the class's outlets.在控制器 #1 中,添加了一个原型单元,将类设置为我的UITableViewCell子类,设置重用 ID,添加标签并将它们连接到类的插座。 In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before.在 Controller #2 中,添加了一个空的原型单元格,将其设置为与以前相同的类并重用 id。 When it runs, the labels never appear when the cells are shown in Controller #2.当它运行时,当单元格显示在控制器 #2 中时,标签永远不会出现。 Works fine in Controller #1.在控制器 #1 中工作正常。

  • Designed each cell type in a different NIB and wired up to the appropriate cell class.在不同的 NIB 中设计每种细胞类型并连接到适当的细胞类别。 In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class.在故事板中,添加了一个空的原型单元格并设置其类并重用 id 来引用我的单元格类。 In controllers' viewDidLoad methods, registered those NIB files for the reuse id.在控制器的viewDidLoad方法中,为重用 ID 注册这些 NIB 文件。 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.将两个控制器中的原型保持为空并设置类并将 id 重用于我的单元类。 Constructed the cells' UI entirely in code.完全在代码中构建单元格的 UI。 Cells work perfectly in all controllers.单元格在所有控制器中都能完美运行。

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

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.归根结底,我想要两件事:在故事板中连接基于 tableview 的流,并以视觉方式而不是在代码中定义单元格布局。 I can't see how to get both of those so far.到目前为止,我不知道如何获得这两个。

As I understand it, you want to:据我了解,您想要:

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

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 why these 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.从本质上讲,故事板只不过是 .xib 文件的集合。 When you load up a table view controller that has some prototype cells out of a storyboard, here's what happens:当您从故事板加载具有一些原型单元格的表视图控制器时,会发生以下情况:

  • 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:] .因此,当表视图控制器加载时,它会遍历每个原型单元格的笔尖并调用-[UITableView registerNib:forCellReuseIdentifier:]
  • The table view asks the controller for the cells.表格视图向控制器询问单元格。
  • You probably call -[UITableView dequeueReusableCellWithIdentifier:]你可能会调用-[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:] .调用[[CellClass alloc] initWithCoder:]
    2. The -initWithCoder: method goes through and adds subviews and sets properties that were defined in the nib. -initWithCoder:方法遍历并添加子视图并设置在笔尖中定义的属性。 ( IBOutlet s probably get hooked up here as well, though I haven't tested that; it may happen in -awakeFromNib ) IBOutlet可能在这里连接,尽管我还没有测试过;它可能发生在-awakeFromNib
  • You configure your cell however you want.您可以根据需要配置您的单元。

The important thing to note here is there is a distinction between the class of the cell and the visual appearance of 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 UITableViewCell styles, this is exactly what's happening.事实上,如果你使用默认的UITableViewCell样式,这正是正在发生的事情。 The "Default" style and the "Subtitle" style, for example, are both represented by the same UITableViewCell class.例如,“默认”样式和“字幕”样式都由同一个UITableViewCell类表示。

This is important : The class of 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 UITableView instance.重用标识符仅在单个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.在控制器 #1 中,添加了一个原型单元,将类设置为我的 UITableViewCell 子类,设置重用 ID,添加标签并将它们连接到类的插座。 In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before.在 Controller #2 中,添加了一个空的原型单元格,将其设置为与以前相同的类并重用 id。 When it runs, the labels never appear when the cells are shown in Controller #2.当它运行时,当单元格显示在控制器 #2 中时,标签永远不会出现。 Works fine in Controller #1.在控制器 #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.虽然两个单元格具有相同的类,但传递给控制器​​ #2 中单元格的视图层次结构完全没有子视图。 So you got an empty cell, which is exactly what you put in the prototype.所以你得到了一个空单元格,这正是你放入原型中的内容。

Designed each cell type in a different NIB and wired up to the appropriate cell class.在不同的 NIB 中设计每种细胞类型并连接到适当的细胞类别。 In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class.在故事板中,添加了一个空的原型单元格并设置其类并重用 id 来引用我的单元格类。 In controllers' viewDidLoad methods, registered those NIB files for the reuse id.在控制器的 viewDidLoad 方法中,为重用 ID 注册这些 NIB 文件。 When shown, cells in both controllers were empty like the prototype.显示时,两个控制器中的单元格都像原型一样是空的。

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 UINib containing the cell, and you'd get back that same cell.正如您所指出的,您可以只以编程方式调用-[UITableView registerNib:forCellReuseIdentifier:] ,传递包含单元格的UINib ,然后您将返回同一个单元格。 (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. (这不是因为原型“覆盖”了笔尖;您只是没有在 tableview 中注册笔尖,所以它仍在查看嵌入在故事板中的笔尖。)不幸的是,这种方法有一个缺陷——无法将故事板 segue 连接到独立笔尖中的单元格。

Kept prototypes in both controllers empty and set class and reuse id to my cell class.将两个控制器中的原型保持为空并设置类并将 id 重用于我的单元类。 Constructed the cells' UI entirely in code.完全在代码中构建单元格的 UI。 Cells work perfectly in all controllers.单元格在所有控制器中都能完美运行。

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.您目前无法将故事板 segue 连接到这些单元格。 Hopefully, though, you've learned something in the process of reading this.不过,希望您在阅读本文的过程中学到了一些东西。

In spite of the great answer by BJ Homer I feel like I have a solution.尽管 BJ Homer 给出了很好的答案,但我觉得我有一个解决方案。 As far as my testing goes, it works.就我的测试而言,它有效。

Concept: Create a custom class for the xib cell.概念:为xib单元创建自定义类。 There you can wait for a touch event and perform the segue programmatically.在那里您可以等待触摸事件并以编程方式执行 segue。 Now all we need is a reference to the controller performing the Segue.现在我们需要的是对执行 Segue 的控制器的引用。 My solution is to set it in tableView:cellForRowAtIndexPath: .我的解决方案是在tableView:cellForRowAtIndexPath:设置它。

Example例子

I have a DetailedTaskCell.xib containing a table cell which I'd like to use in multiple table views:我有一个DetailedTaskCell.xib包含一个表格单元格,我想在多个表格视图中使用它:

详细任务单元.xib

There is a custom class TaskGuessTableCell for that cell:该单元格有一个自定义类TaskGuessTableCell

在此处输入图片说明

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" .我有多个 Segue,但它们都有相同的名称: "FinishedTask" If you need to be flexible here, I suggest to add another property.如果您需要在这里灵活,我建议添加另一个属性。

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!可能有更优雅的方法来实现相同的但 - 它有效! :) :)

I was looking for this and I found this answer by Richard Venable.我正在寻找这个,我找到了 Richard Venable 的答案 It works for me.这个对我有用。

iOS 5 includes a new method on UITableView: registerNib:forCellReuseIdentifier: iOS 5 在 UITableView 上包含了一个新方法:registerNib:forCellReuseIdentifier:

To use it, put a UITableViewCell in a nib.要使用它,请将 UITableViewCell 放入笔尖。 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.您可以在加载 tableView 后注册笔尖,然后当您使用单元格标识符调用 dequeueReusableCellWithIdentifier: 时,它将从笔尖中拉出它,就像您使用 Storyboard 原型单元格一样。

Swift 3斯威夫特 3

BJ Homer gave an excellent explanation, It helps me understand the concept. BJ Homer 给出了很好的解释,它帮助我理解了这个概念。 To make a custom cell reusable in storyboard , which can be used in any TableViewController we have to mix the Storyboard and xib approach.为了make a custom cell reusable in storyboard ,可以在任何 TableViewController 中使用,我们必须mix the Storyboard and xib方法。 Suppose we have a cell named as CustomCell which is to be used in the TableViewControllerOne and TableViewControllerTwo .假设我们有一个名为CustomCell的单元格, CustomCellTableViewControllerOneTableViewControllerTwo 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. 1.文件 > 新建 > 单击文件 > 选择 Cocoa Touch Class > 单击下一步 > 为您的类命名(例如CustomCell )> 选择子类为 UITableVieCell > 勾选还创建 XIB 文件复选框并按下一步。
2. Customize the cell as you want and set the identifier in attribute inspector for cell, here we ll set as CellIdentifier . 2.根据需要自定义单元格并在单元格的属性检查器中设置标识符,这里我们将设置为CellIdentifier This identifier will be used in your ViewController to identify and reuse the Cell.此标识符将在您的 ViewController 中用于识别和重用 Cell。
3. Now we just have to register this cell in our ViewController viewDidLoad . 3.现在我们只需要在我们的 ViewController viewDidLoad register this cell No need of any initialization method.不需要任何初始化方法。
4. Now we can use this custom cell in any tableView. 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!
}

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.从实际的角度来看,我要补充一点,鉴于您不能将单元格作为 xib 并连接 segues,最好的选择是将单元格作为 xib - 转换比跨多个位置的单元格布局和属性更容易维护,无论如何,您的转场很可能与您的不同控制器不同。 You can define the segue directly from your table view controller to the next controller, and perform it in code.您可以直接定义从您的表视图控制器到下一个控制器的转场,并在代码中执行它。 . .

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

I found a way to load the cell for the same VC, not tested for the segues.我找到了一种为同一个 VC 加载单元的方法,没有针对 segue 进行测试。 This could be a workaround for creating the cell in a separate nib这可能是在单独的笔尖中创建单元格的解决方法

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在这里你有故事板中的单元格

If I understand your question correctly, this is fairly easy.如果我正确理解你的问题,这很容易。 Create a UIViewController in your storyboard that will hold your prototype cells and create a static shared instance that loads itself from the storyboard.在你的故事板中创建一个UIViewController来保存你的原型单元格并创建一个从故事板加载自身的静态共享实例。 To handle view controller segues, use the manual segue outlet and trigger on table view delegate didSelectRow (the manual segue outlet is the middle icon at the top of the view controller in the storyboard, in between 'First Responder' and 'Exit').要处理视图控制器转场,请使用手动转场出口并在表视图委托didSelectRow上触发(手动转场出口是故事板中视图控制器顶部的中间图标,位于“第一响应者”和“退出”之间)。

XCode 12.5, iOS 13.6 XCode 12.5,iOS 13.6

// A cell with a single UILabel

class UILabelCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
}

// A cell with a signle UISwitch

class UISwitchCell: UITableViewCell {
    @IBOutlet weak var uiSwitch: UISwitch!
}


// The TableViewController to hold the prototype cells.    

class CellPrototypeTableViewController: UITableViewController {
    
    // Loads the view controller from the storyboard
    
    static let shared: CellPrototypeTableViewController = {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "cellProtoypeVC") as! CellPrototypeTableViewController
        viewController.loadViewIfNeeded()  // Make sure to force view controller to load the view!
        return viewController
    }()

    
    // Helper methods to deque the cells
    
    func dequeUILabeCell() -> UILabelCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "uiLabelCell") as! UILabelCell
        return cell
    }
    
    func dequeUISwitchCell() -> UISwitchCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "uiSwitchCell") as! UISwitchCell
        return cell
    }
}

Use:采用:

class MyTableViewController: UITableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // Dequeue the cells from the shared instance
        
        switch indexPath.row {
        case 0:
            let uiLabelCell = CellPrototypeTableViewController.shared.dequeUILabeCell()
            uiLabelCell.label.text = "Hello World"
            return uiLabelCell
        case 1:
            let uiSwitchCell = CellPrototypeTableViewController.shared.dequeUISwitchCell()
            uiSwitchCell.uiSwitch.isOn = false
            return uiSwitchCell
        default:
            fatalError("IndexPath out of bounds")
        }
    }
    
    // Handling Segues
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0: self.performSegue(withIdentifier: "first", sender: nil)
        case 1: self.performSegue(withIdentifier: "second", sender: nil)
        default:
            fatalError("IndexPath out of bounds")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM