【发布时间】:2021-08-08 12:18:57
【问题描述】:
我想要实现的是这样的布局。
盒子里面还有其他内容,比如图片、文字、按钮等等。我想要的是使盒子尺寸动态化,以便它占据内容的高度。我想到的第一个选项是使用集合视图流布局。
经过反复试验,我最终得到了这个布局。
我的问题是我希望它们之间的项目间距相等,有什么方法可以实现吗? 我非常感谢任何建议。
到目前为止我已经尝试过什么。
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath) as! MyCollectionViewCell
cell.configure(title: data[indexPath.row].title)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let spacing: CGFloat = 10
let numberOfItemsPerRow:CGFloat = 2
let spacingBetweenCells:CGFloat = 10
let totalSpacing = (2 * spacing) + ((numberOfItemsPerRow - 1) * spacingBetweenCells)
let approximateWidthOfContent = view.frame.width - 32
let size = CGSize(width: approximateWidthOfContent, height: 1000)
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
let estimatedFrame = NSString(string: data[indexPath.row].title).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
if let collection = self.collectionView{
let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
return CGSize(width: width, height: estimatedFrame.height + 50)
}else{
return CGSize(width: 0, height: 0)
}
}
}
我知道有类似的问题,但我找不到任何符合我要求的问题。
【问题讨论】:
-
你能贴一些代码吗?会更容易提供帮助
-
当然。我将使用一些示例代码更新问题。
-
你需要继承
UICollectionViewLayout并创建你自己的自定义布局逻辑。 -
@Larme 你能指导我在哪里可以找到一些关于制作自定义布局的教程吗?
-
大量教程。甚至可能在 Github 中存在一个,或者具有您想要的结果。但这意味着您需要进行一些搜索(Google 上的“UICollectionViewLayout Custom”?)。
标签: ios swift uicollectionview uicollectionviewcell