Search code examples
uitableviewsections

swift created sections uitableview


I'm new to swift and object oriented programming,

I'm trying to make some date display in sections in my UI table view

I want to modify the Header of these sections manually

here's my code :

    let section1 =
   ["this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",]
let section2 =
   ["this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",
    "this is used tot test the lenght of the text",]

then my method to load it

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 5
}

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

func tableView(tableView: UITableView,
    cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
    cell.textLabel!.text = section1[indexPath.row]
    cell.textLabel!.numberOfLines = 3

    return cell
}

I have created multiple constant for these but they don't need to be separated (They're constant they won't change)

I just need 5 different sections for my data

thanks a lot


Solution

  • instead of cell for row at index path implement this delegate method:

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
      if section == 0 {
         tableView.headerViewForSection(section)?.textLabel.text = section1[section]
      } else if section == 1 {
         //and so on for the number of sections you need. 5 or what evet.
      }
    

    }