这里有一个可以帮助你的小设置。
Apple 为 UICollectionView 单元格大小提供了几个选项:
1.Autolayout, 2.override sizeThatFits() 或 3.override preferredLayoutAttributesFittingattributes()
您可以观看 WWDC 2016 视频会议 219 了解更多信息。
下面的自动布局选项。
创建了一个带有文本标签的 UICollectionViewCell 子类 xib。
在视图控制器中创建collectionView,添加为子视图,注册xib,设置估计大小为1x1的UICollectionViewFlowLayout。 UICollectionView 将计算开箱即用的高度。
class ViewController: UIViewController {
var collectionView: UICollectionView? {
didSet {
let nib = UINib.init(nibName: "Cell", bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: "Cell")
}
}
let dataSource: [String] = ["test test test test test",
"test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test"]
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = UICollectionViewFlowLayout()
// Don't miss this line, or collectionView will use autosizing by default
flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
let collection = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
view.addSubview(collection)
collectionView = collection
collectionView?.dataSource = self
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.descriptionLabel.text = dataSource[indexPath.row]
return cell
}
}
单元设置:
@IBOutlet weak var widthLayoutConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// We dont need autolayout calculation for width and height of the cell so disabling it
contentView.translatesAutoresizingMaskIntoConstraints = false
// And adding a constant width constraint
let width = UIScreen.main.bounds.size.width
widthLayoutConstraint.constant = width - 24.0 // giving some offsets for the cell: 24 pt
}
另外请注意,此设置不适用于 iOS