Вы должны использовать метод делегата называется collectionView:layout:sizeForItemAtIndexPath
из UICollectionViewDelegateFlowLayout
.
Теперь, фактическая реализация будет зависеть от конкретного случая (это местный контент, если он будет загружен по сети, сколько пользовательских ячеек у вас есть, и т.д.), но вот копия очень простой UICollectionViewController
который работает.
Он использует единую настраиваемую ячейку типа MyAwesomeCell
, которая имеет одну розетку с этикеткой под названием myAwesomeLabel
.
я не сделал каких-либо изменений в раскадровке относительно Preferred Width
, Content Compression Resistance Priority
и т.д. Единственное важное изменение, которое я сделал это установка lines
свойство 0 для метки, что означает неограниченное количество строк.
PS, это было написано в Swift 2.
//
// ViewController.swift
// CollectionCell
//
// Created by Stefan Veis Pennerup on 21/09/15.
// Copyright © 2015 Kumuluzz. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - Constants
struct Constants {
static let ReuseIdentifierMyAwesomeCell = "myAwesomeCell"
}
// MARK: - Models
let myAwesomeCells = [
"Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed massa leo, mollis id tortor at posuere.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper vitae mi vel hendrerit. Suspendisse et feugiat mi. Donec quis sollicitudin quam, non porttitor nulla. Phasellus in luctus lorem, sed auctor enim. Suspendisse potenti. Ut maximus pharetra diam, ac laoreet est dignissim eu nullam."
]
var cellSizes: [CGSize]!
// MARK: - Lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Gives the size array an initial value since collectionView:layout:sizeForItemAtIndexPath
// is called before collectionView:cellForItemAtIndexPath
cellSizes = myAwesomeCells.map({ _ in return CGSize(width: 200, height: 50) })
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Now that the collection view has appeared, then all the cells have been initialized
// with their appropiate content. The view should then be reloaded with the newly
// calculated sizes as well.
collectionView?.reloadData()
}
// MARK: - UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
NSLog("\(self), collectionView:numberOfItemsInSection")
return myAwesomeCells.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
NSLog("\(self), collectionView:cellForItemAtIndexPath")
// Configures the cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.ReuseIdentifierMyAwesomeCell, forIndexPath: indexPath) as! MyAwesomeCell
cell.myAwesomeLabel.text = myAwesomeCells[indexPath.item]
// Calculates the height
cell.setNeedsLayout()
cell.layoutIfNeeded()
cellSizes[indexPath.item] = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
// Returns the new cell
return cell
}
// MARK: - UICollectionViewDelegate
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
NSLog("\(self), collectionView:layout:sizeForItemAtIndexPath")
return cellSizes[indexPath.item]
}
}
Я мог бы использовать это. Я также могу установить максимум символов в метке. У меня есть хорошая идея! Спасибо. –
@ Eri-Sklii Нет проблем. Надеюсь, это сработало для вас. –