I want to have oval shaped collection cells with width based on the label/text length, but I am having trouble making all the cells look oval. I don't know how to resize based on the label's text length.
I am essentially trying to get something like the blank/pink picture below I saw on another post but the solution didn't work. I have also added what my view controller currently looks like.
1) How do I resize to get oval shape correctly and also 2) why are there longer spaces between some cells and how do I fix that?
Storyboard cell (width of label is set to 150)
class HobbiesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
@IBOutlet weak var collectionView: UICollectionView!
var items = ["karateeeeeeeeeee", "signup", "last", "madur", "open", "somelongword", "nice", "looooooooong", "karate", "karate","karate", "signup", "last", "madur"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hobbyCell", for: indexPath) as! HobbiesViewCell
cell.label.text = self.items[indexPath.item]
cell.backgroundColor=UIColor.blue //try with different values untill u get the rounded corners
cell.layer.cornerRadius = cell.bounds.size.height / 2
cell.layer.masksToBounds=true
return cell
}
}
extension HobbiesViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hobbyCell", for: indexPath) as! HobbiesViewCell
cell.label.text = items[indexPath.row]
cell.label.sizeToFit()
return CGSize(width: cell.label.frame.width + 10 , height: 70)
}
}