【问题标题】:Is it possible to create one tableViewCell that can be used in multiple Table Controllers?是否可以创建一个可以在多个表控制器中使用的 tableViewCell?
【发布时间】:2017-10-11 14:56:41
【问题描述】:

我有大约 3 或 4 个表格控制器,它们都将使用相同的表格视图单元格。我继续回到第四个可能的逻辑。假设两者之间的信息相同,我可以在多个 tableView 控制器中使用相同的 tableViewCell 吗?还是我必须为每个控制器创建一个新单元?

【问题讨论】:

    标签: xcode uitableview


    【解决方案1】:

    是的,你可以。

    我假设您使用的是 Swift。

    转到文件 -> 新建并选择 cocoaTouch 类,如下所示。

    现在为自定义单元格命名您的类,并使其成为 UITableViewCell 的子类。还要选中“同时创建 Xib 文件”框

    现在在此 Xib 中设计您的单元格并在其 .Swift 文件中创建插座。假设您有一个看起来像这样的自定义 tableView 单元格

    其中包含标签或 ImageView 或单元格中的任何内容。现在在您的自定义单元格的 swift 文件中,您可以编写这样的方法

    class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> YourCustomTableViewCell {
    let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
    tableView.registerNib(UINib(nibName: "YourCustomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
    
    let cell = tableView.dequeueReusableCellWithIdentifier(kYourCustomTableViewCellIdentifier, forIndexPath: indexPath) as! YourCustomTableViewCell
    
    return cell
    }
    

    现在您可以在应用程序的任何 tableView 中使用此单元格,如下所示

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = YourCustomTableViewCell.cellForTableView(tableView, atIndexPath: indexPath)
    cell.backgroundColor = UIColor.clearColor()
    // do something with your cell
    
    }
    

    希望对你有帮助。

    Swift 3 和 Swift 4 更新:

    class func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> YourCustomTableViewCell {
        let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
        tableView.register(UINib(nibName: "YourCustomTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
    
        let cell = tableView.dequeueReusableCell(withIdentifier: kYourCustomTableViewCellIdentifier, for: indexPath) as! YourCustomTableViewCell
    
        return cell
    }
    

    【讨论】:

    • 非常有帮助!不过我想知道,我将如何开始连接我的 IBOutlets?我是否只需选择一个情节提要单元进行连接?
    • @jonpeter 奥特莱斯什么?如果您正在谈论将您的单元格连接到您的 tableView,那么无需这样做。你只需编写上面的代码,它就会工作。如果您要求将您的组件出口到您的单元,那么我也会更新我的答案。
    • 抱歉延迟回复。我想知道是否/如何将单元格中的标签连接到 tablecell 类
    • 好吧,只需打开自定义类的 Xib 并打开助手编辑器,然后像在 viewController 的类上创建一样创建插座
    【解决方案2】:

    是的,您可以在多个 tableView 控制器中使用表格视图单元格。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2013-04-02
      • 2013-09-21
      • 2011-04-15
      相关资源
      最近更新 更多