Swift - クロージャを利用して初期化をすっきりする
viewDidLoadが肥大化するのは、可読性が悪くなるのでもう嫌だ。
そしてStoryboardを使うのはもっと嫌だ。
ということで僕も最近では流行りに習って、クロージャを利用してプロパティを初期化しています。
下のような感じ。
class ViewController: UIViewController { private var didSetupConstraints = false private let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 75, height: 50) // セルの大きさ layout.minimumLineSpacing = 0 // 垂直方向のアイテム同士の間隔 layout.minimumInteritemSpacing = 5 // 水平方向のアイテム同士の間隔 layout.headerReferenceSize = CGSize.zero // ヘッダーのサイズ layout.footerReferenceSize = CGSize.zero // フッターのサイズ layout.sectionInset = UIEdgeInsetsZero // セクションの上下左右の間隔 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.registerClass(MyCollectionCell.self, forCellWithReuseIdentifier: "MyCollectionCell") collectionView.translatesAutoresizingMaskIntoConstraints = false return collectionView }() // MARK: - UIViewController override func loadView() { self.view = collectionView } override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self } override func updateViewConstraints() { func setupConstraints() { collectionView.topAnchor.constraintEqualToAnchor(topLayoutGuide.topAnchor).active = true collectionView.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor).active = true collectionView.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor).active = true collectionView.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true } if !didSetupConstraints { setupConstraints() didSetupConstraints = true } super.updateViewConstraints() } }
参考: