Search code examples
swiftuitableviewuitabbarcontrollersections

UITableView / Sections : different cells / Swift


I already have the cells in my first section but I don't know how to bring my cell2 specifically just in my second section:

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
        return 4
        }
        if section == 1 {
            return pushUpArray.count
        }
        return section
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell(style: .value1, reuseIdentifier: "section1")
        var cell2 = UITableViewCell(style: .value1, reuseIdentifier: "section2")
        
        
        if cell == nil {
            cell = UITableViewCell(style: .value1, reuseIdentifier: "section1")
        
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        cell.textLabel?.text = TableViewValues[indexPath.row]
        cell.detailTextLabel?.text = TableViewDetailValues[indexPath.row]
        }
        
        if cell2 == nil {
            cell2 = UITableViewCell(style: .value1, reuseIdentifier: "section2")
        }
        cell2.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        cell2.textLabel?.text = "\(indexPath.row). Count: \(count) Time: \(Time)"
        
        
        
        return cell
        return cell2
    }

Thanks in advance!


Solution

  • Return cells depends on section

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 4
        } else {
            return pushUpArray.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = UITableViewCell(style: .value1, reuseIdentifier: "section1")
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
            cell.textLabel?.text = TableViewValues[indexPath.row]
            cell.detailTextLabel?.text = TableViewDetailValues[indexPath.row]
            return cell
        } else {
            let cell2 = UITableViewCell(style: .value1, reuseIdentifier: "section2")
            cell2.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
            cell2.textLabel?.text = "\(indexPath.row). Count: \(count) Time: \(Time)"
            return cell2
        }
    
        return UITableViewCell()
    }