swift
1 @IBOutlet weak var collectionView: UICollectionView!
2
3 override func viewDidLoad() {
4 super.viewDidLoad()
5 collectionView.delegate = self
6 collectionView.dataSource = self
7 // 自作セルをテーブルビューに登録する
8 let chatXib = UINib(nibName: "CommunityChatCollectionViewCell", bundle: nil)
9 collectionView.register(chatXib, forCellWithReuseIdentifier: "communityChatCell")
10
11 let layout = UICollectionViewFlowLayout()
12 layout.itemSize = CGSize(width: collectionView.frame.width, height: 52)
13 layout.minimumLineSpacing = 0
14 layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
15 collectionView.collectionViewLayout = layout
16 }
17
18 func numberOfSections(in collectionView: UICollectionView) -> Int {
19 return 2
20 }
21
22 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
23 return 1
24 }
25
26 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
27 // セル生成
28 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "communityChatCell", for: indexPath) as! CommunityChatCollectionViewCell
29
30 cell.message.text = "This is label one.\nThis is label one.\nThis is label one.\nThis is label one.\nThis is label one."
31 cell.name.text = "This is label two.\nThis is label two.\nThis is label two.\nThis is label two.\nThis is label two."
32 cell.cellWid = collectionView.frame.size.width
33 return cell
34 }
swift
1class CommunityChatCollectionViewCell: UICollectionViewCell {
2
3 @IBOutlet weak var img: UIImageView!
4 @IBOutlet weak var name: UILabel!
5 @IBOutlet weak var message: UILabel!
6
7 @IBOutlet weak var cellWidth: NSLayoutConstraint! {
8 didSet {
9 cellWidth.isActive = true
10 }
11 }
12
13 var cellWid: CGFloat? = nil {
14 didSet {
15 guard let cellWid = cellWid else {
16 return
17 }
18 cellWidth.constant = cellWid
19 }
20 }
21
22 override func awakeFromNib() {
23 super.awakeFromNib()
24 // Initialization code
25
26 NSLayoutConstraint.activate([
27 contentView.leftAnchor.constraint(equalTo: leftAnchor),
28 contentView.rightAnchor.constraint(equalTo: rightAnchor),
29 contentView.topAnchor.constraint(equalTo: topAnchor),
30 contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
31 ])
32
33 }
34}
35
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。