Can I use a single prototype cell in multiple tableViews?

后端 未结 5 1936

I am having two different tableviews in two different controller. But the cells, that I need to display in them, look identical. I have created a prototype cell in one tableView

相关标签:
5条回答
  • 2021-02-05 06:52

    Yes. We can use a prototype cell of ViewControllerA's tableview for tableview of ViewControllerB. Just need to implement the following code in ViewControllerB

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let vc_array = self.navigationController?.viewControllers 
        let view_controller = vc_array![vc_array!.count - 2] as! ViewControllerA
        let cell = view_controller.tableView.dequeueReusableCell(withIdentifier: "ViewControllerA_ID", for: indexPath) as! ViewControllerA
        
        return cell
    }
    

    Here ViewControllerA is the ViewController which contains the tableview with prototype cell, and we are using the same cell on the tableview of ViewControllerB

    0 讨论(0)
  • 2021-02-05 06:52

    I have used the same UITableViewCell in different apps. just copy one TableViewCell to the other app. That is both apps have the same layout and such. The apps don't belong to the same workspace. The setup works nice, no problems or errors.. just don't know if thats good practice.

    0 讨论(0)
  • 2021-02-05 06:56

    K.. I got it. First of all,

    I can NOT use one prototype cell in two different tableview. But, I can use the same tableViewCell subclass in two different tableviews.

    To achieve it, one just have to copy the prototype cell from one controller and paste it as a prototype cell of the other tableview. Class of the pasted tableview remains the same. Just change the reuseIdentifier. and use it.

    Edit: If your cell has a fairly complicated UI, then it makes more sense to create separate xib for the cell alone. Then programmatically register the xib with the table view. That way, you will have only one copy of the cell and much better at maintaining it when there are changes to the ui.

    0 讨论(0)
  • 2021-02-05 06:59

    If you create a custom cell in XIB it should work just fine. However, I suspect the cell's identifier caused the problem. Try to change your cell's identifier for each table view controller.

    If it's not, you might want to post the source code

    0 讨论(0)
  • 2021-02-05 07:14

    You can use same prototype cell in different view controllers, you just need to dequeue it from the tableview of controller in which you designed it.

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let viewControllerInWhichCellWasDefined = tabBarController?.viewControllers?[0]   
      let cell = viewControllerInWhichCellWasDefined.tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)
      return cell
    }
    
    0 讨论(0)
提交回复
热议问题