teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

サンプルコードの追加

2015/08/05 16:05

投稿

Stripe
Stripe

スコア2183

answer CHANGED
@@ -1,1 +1,36 @@
1
- UICollectionViewLayoutのサブクラスを作って、Cellのサイズをカスタマイズしてください。
1
+ UICollectionViewLayoutのサブクラスを作って、Cellのサイズをカスタマイズしてください。
2
+ ---
3
+ サンプルコード
4
+ ```Swift
5
+ import UIKit
6
+
7
+ class CollectionViewLayout: UICollectionViewLayout {
8
+
9
+ override func collectionViewContentSize() -> CGSize {
10
+ let width = self.collectionView!.bounds.width
11
+ let numOfItems = self.collectionView!.numberOfItemsInSection(0)
12
+ let lastAttribute = layoutAttributesForItemAtIndexPath(NSIndexPath(forRow: numOfItems-1, inSection: 0))
13
+ let height = lastAttribute!.frame.maxY + 20
14
+ return CGSizeMake(width, height)
15
+ }
16
+
17
+ override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
18
+ let numOfItems = self.collectionView!.numberOfItemsInSection(0)
19
+ return (0..<numOfItems).map {
20
+ self.layoutAttributesForItemAtIndexPath(NSIndexPath(forRow: $0, inSection: 0))!
21
+ }
22
+ }
23
+
24
+ override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
25
+ let attribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
26
+ let contentWidth = self.collectionView!.bounds.width
27
+ let row = CGFloat(indexPath.row)
28
+ let x:CGFloat = 20.0
29
+ let y:CGFloat = row * (row * 20.0 + 40.0) + 20.0
30
+ let width:CGFloat = contentWidth - 40.0
31
+ let height:CGFloat = row * 40.0 + 40.0
32
+ attribute.frame = CGRectMake(x, y, width, height)
33
+ return attribute
34
+ }
35
+ }
36
+ ```