How to make a Reusavel Tableview?

Asked

Viewed 85 times

1

On 90% of my screens I will need a tableview to fill the content, how can I make this tableview reusable ? I say how I can simplify the insertion of this table in several views, my code is as follows:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  @IBOutlet weak
  var tableView: UITableView!

    var textArray: NSMutableArray! = NSMutableArray()

  override func viewDidLoad() {
    super.viewDidLoad()

    self.textArray.addObject("Exemplo1.")

    self.textArray.addObject("Exemplo2.")

    self.textArray.addObject("Exemplo3.")

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 44.0

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }



  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
    return self.textArray.count;
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {

    var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel ? .text = self.textArray.objectAtIndex(indexPath.row) as ? String

    return cell

  }


}

Outside the work of Main.Storyboard which is to put a tableView, put the auto-layout insert the Identifier and put the @Iboutlet...

1 answer

0


I did not understand your question, but I believe you want to have another tableview on another screen the same way the first, besides mounting it on the storyboard and connecting the outlet’s, just insert the delegate and data source after the declaration of the class, create an array of the objects that will appear in the table and start in viewDidLoad, and then set the numberOfRowsInSection and cellForRowAtIndexPath functions.

  • You understood my question well, I have about 30 viewControllers that I needed to fill each with the same settings, wanted a way to create a class/plugin to make this code more DRY, I say avoid always repeat the same code on multiple screens.

  • In this case I believe that you can only create an Extension class and create some function with an init that returns an array to fill each table and only, because the outlet’s have to be manual because it has to connect code and view, and leave the delegate and the source date with the relevant codes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.