こちらのサイトを参考にCollectionViewControllerを表示するアプリを作ってみました。
以下が記述したコードです。
swift
1import UIKit 2 3class CollectionViewController: UICollectionViewController { 4 5 var dataList = ["青山","阿部","加藤","神田","佐藤","坂田"] 6 7 override func viewDidLoad() { 8 super.viewDidLoad() 9 10 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 11 12 //cellの上下左右の余白。(top,left,bottom,right) 13 layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20) 14 15 } 16 17 override func didReceiveMemoryWarning() { 18 super.didReceiveMemoryWarning() 19 } 20 21 override func numberOfSections(in collectionView: UICollectionView) -> Int { 22 return 1 23 } 24 25 override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 26 return dataList.count 27 } 28 29 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 30 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 31 // Tag番号を使ってLabelのインスタンス生成 32 let label = cell.contentView.viewWithTag(1) as! UILabel 33 label.text = dataList[indexPath.row] 34 35 return cell 36 } 37 38 func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize { 39 40 let cellSize:CGFloat = self.view.bounds.width/2 - 2 41 // 正方形で返すためにwidth,heightを同じにする 42 return CGSize(width: cellSize, height: cellSize) 43 } 44 45 46} 47
画面のようにセル同士の余白はググったりで自力で調節できたのですが、画面の枠?フレームからの余白の調節はどのような方法で調節するのでしょうか?
さらに余白についてググった結果、こちらのサイトが出てきました。
以下は抜粋です。
swift
1 2 //UICollectionViewのレイアウトを生成 3 let layout = UICollectionViewFlowLayout() 4 //cellの上下左右の余白。(top,left,bottom,right) 5 layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20)
私はこちらのコードがそうなんじゃないかと思い自分のコードに組み込もうとしたのですが、こちらのリンクはコードからCollectionViewを作っていて、この部分を使いaddSubviewしてるし、、、同じようにViewdidload内で同じ記述をしたらダブtちゃうし、、など思ったのですが、
CollectionViewControllerでこちらのコード(合ってるかは不明)を使うにはどのメソッドの中でどう記述すればいいのでしょうか?
また、もしかして画面枠からの余白はstoryboardで調整可能なのでしょうか?
質問でわかりずらいことがありましたらおっしゃっていただけると幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/04 01:35