未分類

collectionViewで均等なマス目を作る

投稿日:2020年7月28日 更新日:

セル同士を0.5の線で区切りたいが、所々太くなってしまっている。
ボーダーを非表示にすると、わずかな隙間ができている。
セル同士の隙間を0にすることで、綺麗な0.5のボーダーにしたい。

//セルの大きさ・隙間を調整する関数
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let width: CGFloat = self.view.bounds.width / 7
        let height : CGFloat = width * 1.5
        return CGSize(width: width, height: height)
    }

 

解決策

画面の幅を7で割ると余りが出てしまうのが原因らしい。
余ったピクセルを1pxずつ前から順にセルに割り当てるとよい。

以下のように書き換えた。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                
        let columns = 7
        let width = Int(UIScreen.main.bounds.width)
        let side = width / columns
        let rem = width % columns
        let addOne = indexPath.row % columns < rem
        let cellWidth = addOne ? side + 1 : side
        return CGSize(width: cellWidth, height: side)
    }

参考:https://stackoverflow.com/questions/29441547/uicollectionview-3-column-grid-1px-space-image-included

さらにセルの縦幅を横幅の1.5倍にしたい。
このままsideを1.5倍すると、Int型とDouble型の計算ができないためエラーとなる。
そこでInt型からDouble型に変換する。
CGsizeもwidthとheightの型を合わせる必要があるから、横幅もDouble型に変換する。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let columns = 7
        let width = Int(UIScreen.main.bounds.width)
        let side = width / columns
        let rem = width % columns
        let addOne = indexPath.row % columns < rem
        let cellWidth = addOne ? side + 1 : side
        //Double型に変換
        let dSide:Double = Double(side)
        let dCellHeight = dSide * 1.5
        let dCellWidth:Double = Double(cellWidth)
        return CGSize(width: dCellWidth, height: dCellHeight)
    }

参考:https://i-app-tec.com/ios/int-string-double.html#5

-未分類

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

プレミアプロ講座基礎編1_エフェクト(新規作成時の設定)

新規プロジェクト作成時の設定 プロジェクトを保存する場所を指定 プロジェクトや書き出しを行った時に保存されるフォルダを指定する。 ここを指定すると、オートセーブされるデータのファイルなども全てこのファ …

no image

viewWillAppearについて

super.viewWillAppear(animated)は自分で書く必要あり。 override func viewWillAppear(_ animated: Bool) { super.vie …

no image

TableViewとStaticCellでiPhonの設定画面風を作る

TableViewとStaticCellとNavigationControlleを使って設定画面ぽいものを作るサンプル↓ 参考:UITableView + Static Cellsでアプリ内設定画面を …

no image

プレミアプロ講座応用編3_シェイプやイラストを使ったテロップ

背景や下線のあるテロップ シェイプを追加するだけ。 位置や不透明度等でアニメーションをつけられる。 イラストを使う イラストを使う時に「クロップ」(画像をトリミングする機能)というエフェクトを使う。

no image

実機テストでエラーが出る時の対処法

エラー:Could not locate device support files が出る時 iPhoneのバージョンが今のxcodeのバージョンに対応していないことを示す。 iOSをアップデートする …