ios - 如何配置自定义 UITableViewCell 一次?

标签 ios swift uitableview configuration

考虑我们有

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeViewController.episodeTableViewCellIdentifier, for: indexPath) as! EpisodeTableViewCell

        cell.backgroundColor = UIColor.red
        cell.selectionStyle = .none
        cell.titleLabel.text = episodesArray[indexPath.row].title

        return cell
}

如果我想分离单元格配置部分(设置背景颜色和单元格选择样式),这对于所有单元格都是相同的,以防止每次调用 tableView: cellForRowAt: 时执行这些代码行,该怎么办?

最佳答案

在单元类中创建一个函数。

configure() {
   // setup cell properties here
}

然后你只需要编写 cell.configure() 来代替所有的设置行。

如果您希望它更通用,您可以将此配置函数放在扩展中

extension UITableViewCell {
   func configure() {
     // configure code lines
   }
 }

关于ios - 如何配置自定义 UITableViewCell 一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55055216/

相关文章:

ios - 在 swift-ObjC 中访问扩展中的静态变量

swift - 将 "function with parameter"作为参数传递

ios - 如何获取 tableView 和 tabBar 之间的大小?

objective-c - 将 typedef 转换为 Swift

ios - 如何访问多个自定义表格 View 单元格中的属性

xcode - 使用 xcode 在表格 View 中显示 sqlite3 结果

ios - numberOfRowsInSection 在 iOS8 中被调用了太多次?

ios - Objc 中的 SecRandomCopyBytes 提供程序(SHA1PRNG 或 NativePRNG)类型?

ios - iOS Enterprise Program 是否允许向配置文件添加授权?

swift - 上传到 App Store 时上传失败 ERROR ITMS-90081