【发布时间】:2017-11-24 14:49:33
【问题描述】:
我想在集合视图中的第一个单元格之前添加一些空间,例如偏移量,我的集合视图具有水平滚动位置。
这是我当前的收藏视图:
它的前导约束为 35,我想要的是单元格从 35 的“x”位置开始,但能够像这样滚动全宽:
有没有办法使用 Swift 3 在集合视图中创建初始偏移量?
【问题讨论】:
标签: ios swift uiscrollview uicollectionview uicollectionviewcell
我想在集合视图中的第一个单元格之前添加一些空间,例如偏移量,我的集合视图具有水平滚动位置。
这是我当前的收藏视图:
它的前导约束为 35,我想要的是单元格从 35 的“x”位置开始,但能够像这样滚动全宽:
有没有办法使用 Swift 3 在集合视图中创建初始偏移量?
【问题讨论】:
标签: ios swift uiscrollview uicollectionview uicollectionviewcell
如果您只希望该部分中的单元格具有填充,则按照其他答案中的建议使用来自UICollectionViewFlowLayout 的sectionInset。
但据我猜测,您可能还可以在集合视图本身上设置contentInsets(继承自UIScrollView)
【讨论】:
Swift 5 / Xcode 11
谢谢亚历山大·斯皮里切夫。
根据他的回答,您还可以通过编程方式设置左插图为35分:
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 8
layout.sectionInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0)
collectionView.setCollectionViewLayout(layout, animated: false)
【讨论】:
您可以在collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 中的初始单元格之前设置空格,如下所示:
if (indexPath.row == 0 || indexPath.row == 1) {
// Set value according to user requirements
cell.frame.origin.y = 10
}
【讨论】:
你需要设置 contentInset
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(top, left, bottom, right);
}
可以详细看here
【讨论】:
在这里聚会有点晚了,但我遇到了几个解决方案
正确的方式(滚动到第一个单元格):
https://coderwall.com/p/e-ajeq/uicollectionview-set-initial-contentoffset
简单的hacky方式: 我在第一个项目中添加了一个透明的“间隔”单元格以抵消其余单元格。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
if (indexPath.row == 0) {
cell.backgroundColor = UIColor.white
return cell
}
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if (indexPath.row == 0){
//spacer
return CGSize(width:6, height:50)
}
return CGSize(width: 50, height: 50)
}
【讨论】: