【问题标题】:Should I create a UITableViewCell class to every table in my app?我应该为我的应用程序中的每个表创建一个 UITableViewCell 类吗?
【发布时间】:2020-05-08 15:11:59
【问题描述】:

您好,我是 iOS 开发新手,我在 Xcode 11.0 上使用 swift 5,我知道如何创建表格视图和显示数据,但我有一些与干净代码和最佳实践相关的问题:

1- 我应该为同一张表中的每个单元格创建一个 UITableViewCell 类吗?还是同一张表中所有单元格的一个类?

2- 我可以为不同页面上的不同表格使用相同的 UITableViewCell 类吗?

我看了几个在线教程,但他们都只是解释如何创建一个表,并没有涉及太多细节。

【问题讨论】:

  • 1.如果单元格具有相同的设计,则您应该有一个单元格原型。 2. 是的,你可以。查看 Xcode 中的 tableView 文档,在“为您的表格配置单元格”
  • 一个表格视图可以有不同的单元格,多个表格视图可以有相同的单元格。但您不必这样做,这取决于您的设计。
  • 感谢@claude31 的提示
  • 哦好吧我猜根据设计总结答案,谢谢@koen

标签: ios swift iphone xcode uitableview


【解决方案1】:

对于第一个问题,您实际上可以对不同的单元格使用相同的 UITabelViewCell,这只是一个问题,即它们共享多少设计以及如果区分它们,您将需要重复多少代码。

是的,实际上如果您的 UITabelViewCell 在不同的 TableViews 中使用,那么您需要外部化您的单元格,这意味着您需要将其放在 Xib 中的 TableView 之外或以编程方式创建,然后在您的每个 TableView 中像这样注册该单元格会用的。

//Created programmatically
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell-identifier")

//From a Xib
tableView.register(UINib(nibName: "Nib-identifier", bundle: nil), forCellReuseIdentifier: "cell-identifier")

注意:将标识符放在类内的静态变量中(如果有的话,也可以是您的 nib),如下所示:

//  https://gist.github.com/JCTec/e64e34e204a6bb99ef92f73b2ee0ee7d
//  String+LoadNib.swift
//  Created by Juan Carlos Estevez on 17/12/19.
extension String {
    /// Carga un Archivo Nib con el nombre de la cadena de texto.
    ///
    /// - Parameter bundle: Bundle a agregar.
    /// - Returns: UINib.
    func loadNib(bundle: Bundle? = nil) -> UINib? {
        return UINib(nibName: self, bundle: bundle)
    }
}


class MyTableViewCell: UITableViewCell {
    static let identifier: String = "cell-identifier"
    static var nib: UINib! = {
        return "nib-identifier".loadNib()
    }()
}

//Use it like this
//Created programmatically
tableView.register(MyTableViewCell.self, forCellReuseIdentifier: MyTableViewCell.identifier)

//From a Xib
tableView.register(MyTableViewCell.nib, forCellReuseIdentifier: MyTableViewCell.identifier)

【讨论】:

  • 顺便说一句,欢迎来到 iOS 开发?。 CollectionView 也和 TableView 一样但是有更多的技巧,考虑使用比 TableViews 更多的 CollectionViews。 @S.Hasan
  • 工作得很好,谢谢你的解释,我现在做得更好了。感谢 CollectionView 的提示,我会查一下 (Y) @Juan Carlos
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多