首页 > 解决方案 > 我们可以在 swift 的 UITableView 部分中实现部分吗?

问题描述

假设有 aUITableView有 2 个部分 A 和 B。现在在两个部分中,要显示多个对象的详细信息,例如,如果对象是汽车,那么有多个汽车,名称、颜色、里程要显示在物体。那么如何以最佳方式解决问题,因为我们必须使用它来实现它UITableView

我提供了 2 个部分UITableView。然后,我将对象显示为部分内的行。然后,如果我只显示一个对象的 3 个详细信息,那么我将提供行数为 3*(对象数)。下面的代码写在UITableViewCell类内部,并通过UIViewController持有UITableView对象的数据源方法 cellForRowAt()调用

func configureSectionACellWith(indexPath: IndexPath, data: [Car]) {
   var row = indexPath.row
   row = row % 3
   switch row {
   case 0: carNameLabel.text = data[indexPath.row/3].name
   case 1: colorLabel.text = data[indexPath.row/3].color
   case 2: mileageLabel.text = data[indexPath.row/3].mileage
   default:
       break
   }
}

同样,为了配置Section B的单元格,重复上面的代码。

但正如您可能看到的,很多东西都是硬编码的,比如 row = row % 3,新开发人员很难理解代码。还有重复的代码(配置部分 A 和 B 的单元格)。有没有其他方法,当然是解决这种情况的最佳方法?

标签: iosswiftuitableview

解决方案


If the layout/details are likely to be the same for each Section, you can just create one type of cell and use it in both section:

class DetailCell: UITableViewCell {
  static let cellID = "DetailCell"
 //set up all the images/labels etc

  func configure(with car: Car) {
    label1.text = car.name
    label2.text = car.color
    label3.text = car.mileage
  }
  func configure(with other: SomeOtherType) {. //whatever Section B displays
    label1.text = other.property1
    label2.text = other.property2
    label3.text = other.property3
  }
}

You don't need to worry about indexpaths or rows for the cell definition. That's done in the dataSource & delegate functions.

You'll set the number of rows in each section the UITableViewDataSource's numberOfRows method, and create all your cells in the cellForRowAt method. I'll not repeat all the detail here - there are 100s of tutorials and blogs on tableViews - but will give you summary examples so you know what you're heading towards:

override func viewDidLoad() {
   super.viewDidLoad()
   tableView.register(DetailCell.self, forCellReuseIdentifier: DetailCell.cellID)
   //any other setup
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   switch section :
   case 0: return carsArray.count //if you're showing cars in section A
   case 1: return someOtherArray.count //whatever you;re showing in section B
   default: return 0
   }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: DetailCell.cellID, for: indexPath)
  if indexPath.section == 0 {
    cell.configure(with: carsArray[indexPath.row])
  } else if section == 1 {
    cell.configure(with: someOtherArray[indexPath.row])
  }
  //do any further cell set up
  return cell
}

推荐阅读