gpt4 book ai didi

ios - UICollectionview 动态适应一行

转载 作者:行者123 更新时间:2023-11-30 12:26:55 24 4
gpt4 key购买 nike

我有来自服务器的单词,并且动态地设置了 Collection View ,每个单元格显示一个字母。

但是如果单词太长,那么所有内容都会缩小。

enter image description here enter image description here

我希望每个字母都适合 Collection View ,单词应该只适合一行,所以我使用了:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfSets = CGFloat(self.letters!.count)
let width = (collectionView.frame.size.width - (numberOfSets * view.frame.size.width / 15))/numberOfSets
let height = collectionView.frame.size.height / 2
return CGSize(width : width, height : height)
}

最佳答案

我认为您需要的是保持单元格左对齐,并具有固定的单元格宽度和单元格之间的填充。当字母很少时,不是动态填充。你不希望“a b c”变成“a........b........c”。解决方案是在单元格之间设置最大填充,不幸的是,默认 Collection View 布局没有这样的设置。您需要定义一个:

class MaxSpacingCollectionViewFlowLayout : UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else {
return nil
}

if attributes.count <= 0 { return attributes }

let firstCellOriginX = attributes[0].frame.origin.x

for i in 1..<attributes.count {
let currentLayoutAttributes = attributes[i];
if currentLayoutAttributes.frame.origin.x == firstCellOriginX {
continue //first cell of a new row
}

let prevLayoutAttributes = attributes[i - 1]
let prevOriginMaxX = prevLayoutAttributes.frame.maxX
if currentLayoutAttributes.frame.origin.x - prevOriginMaxX > 8 { // 8 here is the max padding
var frame = currentLayoutAttributes.frame
frame.origin.x = prevOriginMaxX + 8
currentLayoutAttributes.frame = frame
}
}

return attributes
}
}

然后替换默认布局:

  let collectionView = UICollectionView()
//......
collectionView.collectionViewLayout = MaxSpacingCollectionViewFlowLayout()

最后,委托(delegate)方法 sizeForItemAt 可以简单地返回固定宽度:

  return CGSize(width : 35, height : 35)

关于ios - UICollectionview 动态适应一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com