Search code examples
uitableviewcell

Problem selecting UITableViewCell in Swift


I'm new programming in Swift. I have this tableview populated with json data through Alamofire, but I have two problems. I don't know how to add space between cells, the space that I have with my value called "cellSpacingHeight" is an space between sections, but not between cells in the same section. My other problem is that when I tap a cell, I go to my other View Controller called WorkViewController but always saving the data of the last object of the json data in vc.zoneName = projects.name. What I really need is to tap a cell and go to WorkViewController with the value of the zoneName associated to the cell that I tapped. I would really appreciate answers with lines of code.


Solution

  • Cell spacing:

    I don't think there is a simple way to set cell spacing, what you can do is increase the cell height using the tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat method. For example, if your cell needs to have a height of 100 and a top+bottom margins of 5, you can implement the method like this:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110
    }
    

    Then on your cell ProjectTableView:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let currentItem = array_item[indexPath.row]
         let dicProject = currentItem as! NSDictionary
         let cellProject = projectsTable.dequeueReusableCell(withIdentifier: "cellProject", for: indexPath) as! ProjectTableViewCell
    
         // Add the padding
         cellProject.contentView.layoutMargins = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)
    

    ZoneName on cell tap:

    Assuming the values presented on the cells are all on the array_item array, you only need to get the array object associated with the cell index and then get the value and assign it to the view controller like this, before presenting the WorkZoneViewController:

    let rowItem = array_item[indexPath.row]
    vc.zoneName = rowItem.zoneName