gpt4 book ai didi

ios - 如何在自定义 UICollectionViewLayout 中仅允许垂直和水平滑动

转载 作者:行者123 更新时间:2023-11-30 13:54:06 25 4
gpt4 key购买 nike

请帮我解决这个问题,我正在关注这个tutorial要制作自定义 UICollectionViewLayout,用户可以水平滑动以浏览各个部分,垂直滑动以显示项目。

我的问题是,我只希望用户在 UICollectionView 上垂直或水平滑动,而不是自由滑动。任何关于如何实现这一目标的想法将不胜感激。

这是代码

import UIKit

class moviesLayout: UICollectionViewLayout {

let CELL_HEIGHT = 307.0
let CELL_WIDTH = 204.0

var cellAttrDict = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()

var contentSize = CGSizeZero

var dataSourceDidUpdate = true

override func collectionViewContentSize() -> CGSize {

return contentSize
}

override func prepareLayout() {

if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
if collectionView?.numberOfItemsInSection(section) > 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
let cellIndex = NSIndexPath(forItem: item, inSection: section)
let xPos = Double(item) * CELL_WIDTH
let yPos = Double(section) * CELL_HEIGHT

var cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)
cellAttributes.zIndex = 1
cellAttrDict[cellIndex] = cellAttributes
}
}
}
}

let contentWidth = Double(collectionView!.numberOfItemsInSection(0)) * CELL_WIDTH
let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
self.contentSize = CGSize(width: contentWidth, height: contentHeight)

}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

var attributesInRect = [UICollectionViewLayoutAttributes]()

for cellAttributes in cellAttrDict.values {
if CGRectIntersectsRect(rect, cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}

return attributesInRect
}

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return cellAttrDict[indexPath]!
}

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}

}

最佳答案

使用滑动手势识别器来触发方向变化的传统 flowLayout 怎么样?

var layout = UICollectionViewFlowLayout()

//Hook to two Swipe Gesture Recognizers - Up and Down
@IBAction func verticalSwipe(sender: AnyObject) {
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
self.collectionView?.collectionViewLayout = layout
}

//Hook to two Swipe Gesture Recognizers - Left and Right
@IBAction func horizontalSwipe(sender: AnyObject) {
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView?.collectionViewLayout = layout
}

关于ios - 如何在自定义 UICollectionViewLayout 中仅允许垂直和水平滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881931/

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