Poli97
Poli97

Reputation: 304

Tableview cell padding and spacing

I have this table with cells which have an image and a text enter image description here

First thing that I want is to add a padding to cells so that the image with the circle and the scissors doesn't hit the border of the cell. I already tried things like cell.layoutMargins = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50) or cell.bounds = CGRect(x: 0, y: 0, width: 100, height: 100), cell.separatorInset = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100) but nothing has changed.

Second thing that I would like is to add a spacing between the cell, I tried all the solutions that I found but it doesn't seem to work

CODE (some of the solutions that I tried are written below all toghether, but I also tried them one by time)

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "difficultyCell", for: indexPath)
        cell.textLabel?.text = myDict[indexPath.row].key 
        cell.textLabel?.font = .boldSystemFont(ofSize: 20)
        let imageCell = UIImage(named: "scissors.png")
        cell.imageView?.image = imageCell
        cell.backgroundColor = Esercizio.hexStringToUIColor(hex: "#4cf584").withAlphaComponent(0.85)
        cell.layer.borderColor = UIColor.orange.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8
        cell.layoutMargins = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
        cell.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
        cell.separatorInset = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
        return cell
    }

Upvotes: 0

Views: 4698

Answers (2)

Nathenael Tarek
Nathenael Tarek

Reputation: 165

to solve it easily , if you are using custom UITableViewCell file, in your cell class override the layoutsubView method of the class and there you can add the UIEdgeInset to the frame of the contentView, and also dont forget the added padding amount into total RowHeight estimation in your tableview: this code will work for you for sure,

override func layoutSubviews() {
   super.layoutSubviews()
    contentView.frame = contentView.frame.inset(by:  UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0))
    }

this way you can create padding to whatever direction you want to add the padding.

Upvotes: 1

Michael Long
Michael Long

Reputation: 1102

The best solution here is to create your own cell, add your own image, labels, etc. inside of contentView and tweak them how you want using auto layout constraints.

see: https://www.raywenderlich.com/8549-self-sizing-table-view-cells

Upvotes: 0

Related Questions