【发布时间】:2021-06-15 20:21:17
【问题描述】:
我是新来的,实际上我还没有找到如何设置两行水平collectionView Items的答案。我已经创建了标签项 CollectionView 并且作为一行它工作得很好。但我想把它分成两行,但它也水平滚动。我在 tableview 中使用 collectionView 来查看部分。
根据文本标记项目宽度。
我找到了一个库 TTGTagCollectionView,但那是在目标 C 中。
如果我增加 collectionView 的高度,则会附加更新的图像,它会带来额外的间距和对齐问题。附上图片。
请任何人指导我。我该如何解决这个问题? 在我的代码下面
class TagTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var Data = ["AutoLayout","A","Roman","List of Collections","calculates","Grid","TableView","CollectionView","B","view","Apple","IPhone"]
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
func setup() {
collectionView?.register(UINib(nibName: "TagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TagCollectionViewCell")
let collectionFlowLayout = UICollectionViewFlowLayout()
collectionFlowLayout.scrollDirection = .horizontal
collectionView.setCollectionViewLayout(collectionFlowLayout, animated: true)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.contentInset = UIEdgeInsets(top: 2, left: 10, bottom: 0, right: 10)
collectionFlowLayout.minimumInteritemSpacing = 5
}
}
extension TagTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as! TagCollectionViewCell
let dic = Data[indexPath.row]
cell.lbl?.text = dic
cell.backgroundColor = .lightGray
cell.layer.cornerRadius = 8
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let dic = Data[indexPath.row]
return CGSize(width: self.estimatedFrame(text: dic, font: UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.thin)), height: 50)
}
func estimatedFrame(text: String, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: 0.0)
let boundingBox = NSString(string: text).boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [NSAttributedString.Key.font: font],
context: nil)
return boundingBox.size.width + 20.0
}
}
tableCell、结果图像和来自 TTGTagCollectionView 的最后一个图像 tablecell
【问题讨论】:
标签: swift uitableview uicollectionview uicollectionviewlayout uicollectionviewflowlayout