Search code examples
iosswiftuitableviewgrouped-table

Corner radius not properly fit in dynamic grouped tableView swift


I have created a Grouped TableView dynamically based on data. Based on data tableView cell generated automatic height so every cell has different rowHeight. I have set it accordingly by using self.tableView.rowHeight = 50

But Issue is I am using corner radius, but I don't want to use corner radius on every cell. I am using grayBox UIView and all cells displayed in it. Corner radius apply to start of cell or grayBox and only at end of cell of grayBox but it applied to every cell. How can I do that corner radıus apply on start and bottom?

viewDidLoad() code for tableView Row Height

self.tableView.rowHeight = 50

Dynamic Grouped TableView code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell()      
        cell.backgroundColor = UIColor.clear
        cell.selectionStyle = .none
        let grayBox = UIView(frame: CGRect(x: 5, y: 0, width: self.view.frame.size.width - 11, height: 50))
        grayBox.backgroundColor = ("#cfd8dc").toColor()
        grayBox.layer.cornerRadius = 5
        grayBox.layer.borderColor = UIColor(red:0.80, green:0.80, blue:0.80, alpha:1.0).cgColor
        grayBox.layer.borderWidth = 1.0
        cell.contentView.addSubview(grayBox)

        return cell

    }

Solution

  • 1- Use dequeue

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    

    Instead of

    let cell = UITableViewCell()     
    

    2- Clear subviews here by removing with tag

    let grayBox = UIView(frame: CGRect(x: 5, y: 0, width: self.view.frame.size.width - 11, height: 50))
    grayBox.tag = 333
    cell.contentView.subviews.forEach { 
       if $0.tag == 333 {
          $0.removeFromSuperview()
       }
    } 
    cell.contentView.addSubview(grayBox)
    

    3- For corner raduis

    if  indexPath.row == 0 || indexPath.row == arr.count - 1 {
       grayBox.layer.cornerRadius = 5
    }
    else {
      grayBox.layer.cornerRadius = 0
    }