spacing between UITableViewCells swift3
Solution 1
Update: UIEdgeInsetsInsetRect method is replaced now you can do it like this
contentView.frame = contentView.frame.inset(by: margins)
Swift 4 answer:
in your custom cell class add this function
override func layoutSubviews() {
super.layoutSubviews()
//set the values for top,left,bottom,right margins
let margins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, margins)
}
You can change values as per your need
***** Note ***** calling super function
super.layoutSubviews()
is very important otherwise you will get into strange issues
Solution 2
- From Storyboard, your view hierarchy should be like this.
View CellContent
(as highlighted) will contain all the components.
Give margin to
View CellContent
of 10px from top, bottom, leading & trailing from its superview.Now, select the
tblCell
and change the background color.
- Now run your project, make sure delegate and datasource are properly binded.
OUTPUT
NOTE: I just added 1 UILabel
in View CellContent
for dummy purpose.
Solution 3
If you are using UITableViewCell
to achieve this kind of layout, there is no provision to provide spacing between UITableViewCells
.
Here are the options you can choose:
- Create a custom
UIView
withinUITableViewCell
withclear background
, so that it appears like the spacing between cells.
You need to set the background as clear
of: cell, content view
.
- You can use
UICollectionView
instead ofUITableView
. It is much more flexible and you can design it the way you want.
Let me know if you want any more details regarding this.
Solution 4
One simple way is collection view instead of table view and give cell spacing to collection view and use
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let widthSize = collectionView.frame.size.width / 1
return CGSize(width: widthSize-2, height: widthSize+20)
}
And if you want tableview only then add background view as container view and set background color white and cell background color clear color set backround view of cell leading, trilling, bottom to 10
backgroundView.layer.cornerRadius = 2.0
backgroundView.layer.masksToBounds = false
backgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
![Ankit Kumawat](https://lh5.googleusercontent.com/-xGyc6GRyY3I/AAAAAAAAAAI/AAAAAAAAA8I/0JGpci1rkOA/photo.jpg?sz=256)