ячейка UICollectionView по центру, почему? - PullRequest
0 голосов
/ 21 декабря 2018

У меня была проблема с collectionView.Фактически, у меня был такой алгоритм:
- ширина первой ячейки равна screen_width / 2
- ширина второй ячейки: screen_width
- ширина третьей ячейки равна screen_width / 2
- четвертая ячейкаширина: screen_width.

и т. Д.

Это мой код в методе

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath:

    userStory.typePhotoStory = ( (indexPath.row + 1) % 3) == 0 ? @"landscape" : ((indexPath.row + 1) % 3) == 1 ? @"portrait": @"landscape";
    if ([userStory.typePhotoStory isEqualToString:@"portrait"]) {
        cellSizeFinalWidth = cellSize / 2 ;
        cellSizeFinalHeight = cellSizeFinalWidth + 20 ;
    } else {
        cellSizeFinalWidth = cellSize + padding ;
        cellSizeFinalHeight = cellSize / 2 + 20 ;
    }
}

Но я вижу, что первая и третья ячейка расположены в центреэкран, не запущенный слева.Пожалуйста, помогите мне в этом вопросе?

1 Ответ

0 голосов
/ 21 декабря 2018

Вы можете напрямую использовать этот код,

  1. Создайте новый файл и вставьте этот код ниже для пользовательского макета.

    import UIKit
    
    protocol NewLayoutDelegate: class {
        func collectionView(_ collectionView:UICollectionView, SizeOfCellAtIndexPath indexPath:IndexPath) -> CGSize
    }
    
    
    class NewFlowLayout: UICollectionViewFlowLayout {
    
        weak var delegate : NewLayoutDelegate?
    
        fileprivate var numberOfColumns = 1
        fileprivate var cellPadding: CGFloat = 6
        fileprivate var cache = [UICollectionViewLayoutAttributes]()
    
    
        fileprivate var contentHeight: CGFloat = 0
    
        fileprivate var contentWidth: CGFloat {
            guard let collectionView = collectionView else {
                return 0
            }
            let insets = collectionView.contentInset
            return collectionView.bounds.width - (insets.left + insets.right)
        }
    
        override var collectionViewContentSize: CGSize {
            return CGSize(width: contentWidth, height: contentHeight)
        }
    
        override func prepare() {
            super.prepare()
    
            guard cache.isEmpty == true, let collectionView = collectionView else {
                return
            }
    
            let xOffset : CGFloat = 0
            let column = 0
            var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)
    
            for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
    
                let indexPath = IndexPath(item: item, section: 0)
                let aSize = delegate?.collectionView(collectionView, SizeOfCellAtIndexPath: indexPath)
                let height = cellPadding * 2 + (aSize?.height)!
                let frame = CGRect(x: xOffset, y: yOffset[column], width: (aSize?.width)!, height: height)
                let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
    
                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                attributes.frame = insetFrame
                cache.append(attributes)
    
                contentHeight = max(contentHeight, frame.maxY)
                yOffset[column] = yOffset[column] + height
    
    
            }
        }
    
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    
            var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
    
            for attributes in cache {
                if attributes.frame.intersects(rect) {
                    visibleLayoutAttributes.append(attributes)
                }
            }
            return visibleLayoutAttributes
        }
    
        override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            return cache[indexPath.item]
        }
    
    }
    
  2. В вашем файле контроллера

    import UIKit
    
    class NewCell: UICollectionViewCell {
    
    }
    
    class NewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, NewLayoutDelegate {
    
        @IBOutlet weak var myCollectionView: UICollectionView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            myCollectionView.collectionViewLayout = NewFlowLayout()
    
            if let layout = myCollectionView.collectionViewLayout as? NewFlowLayout {
                layout.delegate = self
            }
    
        }
    
        // Do size logic here
        func collectionView(_ collectionView: UICollectionView, SizeOfCellAtIndexPath indexPath: IndexPath) -> CGSize {
    
            let insets = collectionView.contentInset
    
            if indexPath.item % 2 == 0 {
                return CGSize(width: (collectionView.frame.size.width - (insets.left + insets.right))/2,
                              height: 60)
            }
    
            return CGSize(width: collectionView.frame.size.width - (insets.left + insets.right),
                          height: 60)
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 10
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewCell", for: indexPath) as! NewCell
    
            return cell
        }
    }
    
  3. Выход

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...