Как настроить горизонтальный UICollectionView с разбивкой по страницам, но элементы на странице располагаются слева направо и сверху вниз - PullRequest
3 голосов
/ 20 июня 2019

Я выполнил полную настройку Horizontal UICollectionView с подкачкой, но в настоящее время элементы на странице располагаются сверху вниз и слева направо. Теперь я хочу, чтобы элементы располагались слева направо и сверху вниз.

Пример:

в настоящее время:

      page 1             page 2
 cell 1 | cell 3 || cell 5 | cell 7
 cell 2 | cell 4 || cell 6 | cell 8

мои ожидания:

      page 1             page 2
 cell 1 | cell 2 || cell 5 | cell 6
 cell 3 | cell 4 || cell 7 | cell 8

Я много дней находил решения, но у меня не было результата в SWIFT для моего случая.


Это мой скриншот:

Снимок экрана 1

Снимок экрана 2


мой исходный код на git: https://github.com/lhvan89/UICollectionview

//
//  ViewController.swift
//  CollectionView
//
//  Created by mac on 6/19/19.
//  Copyright © 2019 lhvan89. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var itemsCollectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!

    private let numberOfItemPerpage = 15

    var listItems: [Item] = [
        Item(title: "Behance", image: "behance", badge: 0),
        Item(title: "Deviantart", image: "deviantart", badge: 1),
        Item(title: "Dribbble", image: "dribbble", badge: 2),
        Item(title: "Dropbox", image: "dropbox", badge: 3),
        Item(title: "Facebook", image: "facebook", badge: 4),
        Item(title: "Flickr", image: "flickr", badge: 5),
        Item(title: "Foursquare", image: "foursquare", badge: 6),
        Item(title: "Google-plus", image: "google-plus", badge: 7),
        Item(title: "Instagram", image: "instagram", badge: 8),
        Item(title: "Line", image: "line", badge: 9),
        Item(title: "Linkedin", image: "linkedin", badge: 10),
        Item(title: "Myspace", image: "myspace", badge: 11),
        Item(title: "Path", image: "path", badge: 12),
        Item(title: "Pinterest", image: "pinterest", badge: 13),
        Item(title: "Quora", image: "quora", badge: 14),
        Item(title: "Skype", image: "skype", badge: 15),
        Item(title: "Snapchat", image: "snapchat", badge: 16),
        Item(title: "Soundcloud", image: "soundcloud", badge: 17),
        Item(title: "Spotify", image: "spotify", badge: 18),
        Item(title: "Swarm", image: "swarm", badge: 19),
        Item(title: "Telegram", image: "telegram", badge: 20),
        Item(title: "Tumblr", image: "tumblr", badge: 21),
        Item(title: "Twitter", image: "twitter", badge: 22),
        Item(title: "Viber", image: "viber", badge: 23),
        Item(title: "Vimeo", image: "vimeo", badge: 24),
        Item(title: "Vine", image: "vine", badge: 25),
        Item(title: "Whatsapp", image: "whatsapp", badge: 26),
        Item(title: "Yelp", image: "yelp", badge: 27),
        Item(title: "Youtube", image: "youtube", badge: 28),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        itemsCollectionView.dataSource = self
        itemsCollectionView.delegate = self

         pageControl.numberOfPages = listItems.count/numberOfItemPerpage + (listItems.count % numberOfItemPerpage == 0 ? 0 : 1)

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        itemsCollectionView.reloadData()
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listItems.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCollectionViewCell", for: indexPath) as? itemCollectionViewCell else { return UICollectionViewCell() }
        cell.loadData(item: listItems[indexPath.row])
        return cell
    }
}

extension ViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let x = scrollView.contentOffset.x
        let w = scrollView.bounds.size.width
        let currentPage = Int(ceil(x/w))
        self.pageControl.currentPage = currentPage
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemWidth = collectionView.frame.size.width / 3
        let itemHeight = (collectionView.frame.size.height / 5) - 4
        return CGSize(width: itemWidth, height: itemHeight)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

}

Спасибо за любую помощь!

1 Ответ

2 голосов
/ 20 июня 2019

Создание настраиваемой ячейки представления коллекции, которая принимает массив, состоящий из четырех моделей:

|пункт 1 |пункт 2 |

|пункт 3 |item 4 |

Зарегистрируйте это для просмотра вашей коллекции.Сконфигурируйте его с вашими данными (элемент настройки 1 с первым элементом массива моделей, второй - со вторым элементом массива моделей ...).

Теперь ваша коллекция имеет 2 ячейки и 2 массива моделей в описанном случаевами:

ячейка 1:

|пункт 1 |пункт 2 |

|пункт 3 |элемент 4 |

ячейка 2:

|пункт 5 |пункт 6 |

|пункт 7 |item 8 |

models1: [данные для item1, данные для item2, данные для item3, данные для item4]

models2: [данные для item5, данные для item6, данные для item7, данныедля item8]

//////////////////////

Еще одно более простое решение - реорганизация источника данных:

[data1, data2, data3, data4, data5, data6, data7, data8]

->

[data1, data3, data2, data4, data5, data7, data6, data8]

Код для переупорядочения (работает для вашего индивидуального случая с 4 элементами на одной странице,! Не универсально!):

import Foundation

func rearranged(_ data: [Int]) -> [Int] {
    var result = data
    var i = 0
    while i + 1 < data.count {
        if (i + 1) % 2 == 0 && (i + 1) % 4 != 0 {
            let tmp = data[i]
            result[i] = result[i + 1]
            result[i + 1] = tmp
            i += 1
        }
        i += 1
    }
    return result
}
var dataFromServer: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
let data = rearranged(dataFromServer)
print(data)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...