Reputation: 17882
I'm working on an tvOS app, I want to fix all cells in tv screen without scroll vertically or horizontally. Here cells count will count is dynamic, that's the main problem. I want to set all cells like this
For example: If cell count is 4
If cell count is 5
If cell count is 9
If cell count is 11
Here dynamically need to set column's and row's and cell height and width.(Scroll not allowed)
My code is :
//Example array
var collectionViewArray:[UIColor] = [.brown, .red, .purple, .lightGray, .yellow, .black, .cyan, .magenta, .orange, .purple, .lightGray]
override func viewDidAppear(_ animated: Bool) {
myCollectionView.delegate = self
myCollectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionViewArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TVMenuCollectionViewCell
cell.cellView.backgroundColor = collectionViewArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenWidth = collectionView.bounds.width
let screenHeight = collectionView.bounds.height
return CGSize(width: (screenWidth-50)/4, height: (screenHeight-40)/3)
}
Actually if cells are more number, i need N x (N-1) Column's and row's.
Upvotes: 2
Views: 116
Reputation: 3924
Working code Swift 4
You need to use UICollectionViewDelegateFlowLayout method like this
class CardListViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
// UICollectionViewDelegateFlowLayout Delegate method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let screenWidth = collectionView.bounds.width
let screenHeight = collectionView.bounds.height
if 0 ... 4 ~= collectionViewArray.count{
return CGSize(width: (screenWidth - 30) / 2, height: (screenHeight - 30) / 2)
}else if 5 ... 9 ~= collectionViewArray.count{
return CGSize(width: (screenWidth - 40) / 3, height: (screenHeight - 40) / 2)
}else{
return CGSize(width: (screenWidth - 50) / 4, height: (screenHeight - 50) / 2)
}
}
}
From the Storyboard Set Section Insets Like this.
Output
Upvotes: 1