我有一个收集视图,需要根据标签大小自动设置其单元格宽度。我尝试了很多方法,但是似乎没有一种方法对我有用。
这是原来的样子:https://ibb.co/Nn0BtyG
这就是我要去的地方:https://ibb.co/ckKk9R5
这是我添加自动调整大小代码后的样子:https://ibb.co/vLSyCD6
自动调整大小的代码:
// Layout
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
if #available(iOS 10.0, *) {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
} else {
layout.estimatedItemSize = CGSize(width: self.tagsCollectionView.bounds.width, height: 50)
}
self.tagsCollectionView.collectionViewLayout = layout
这是我的完整代码:
import UIKit
class TagsCollection: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate{
let reuseIdentifier = "TagCell" // also enter this string as the cell identifier in the storyboard
var arrayOfTags: [String] = Array()
var phassetID : String!
func displayTags(){
do{
let assetId = phassetID
let allImagesTagsData = try [Images]()
let assetIndex = allImagesTagsData.firstIndex(where: { $0.id == assetId })
if assetIndex != nil{
arrayOfTags = Array(allImagesTagsData[assetIndex!].tags)
}
}catch{
print("Tag Display View Error: \(error)")
}
}
func setAssetID(assetID: String){
phassetID = assetID
}
override func awakeFromNib() {
self.dataSource = self
self.delegate = self
}
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
displayTags()
return arrayOfTags.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! TagCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = arrayOfTags[indexPath.item]
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
如您所见,我尚未在委托处使用sizeforItem来设置任何位置的单元格大小。有任何想法吗?谢谢