「Swift」ViewControllerセルのサイズを調整する

書式
extension ViewController: UICollectionViewDelegateFlowLayout
UICollectionViewDelegateFlowLayoutを利用してセルのサイズを調整します。画面サイズに合ったセルサイズを計算します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
extension ViewController: UICollectionViewDelegateFlowLayout {
// セルサイズを指定する
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 横方向2列でセルを並べ
let cellSizeWidth:CGFloat = self.view.frame.width/2
// 縦の高さは横幅の半分
return CGSize(width: cellSizeWidth, height: cellWidth/2)
}
}
extension ViewController: UICollectionViewDelegateFlowLayout { // セルサイズを指定する func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // 横方向2列でセルを並べ let cellSizeWidth:CGFloat = self.view.frame.width/2 // 縦の高さは横幅の半分 return CGSize(width: cellSizeWidth, height: cellWidth/2) } }
extension ViewController: UICollectionViewDelegateFlowLayout {

    // セルサイズを指定する
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        // 横方向2列でセルを並べ
        let cellSizeWidth:CGFloat = self.view.frame.width/2
    
        // 縦の高さは横幅の半分
        return CGSize(width: cellSizeWidth, height: cellWidth/2)
    }        
}

結果
横2列でセルを並べます。

Swift

Posted by arkgame