Подтвердить что ты не робот

Множественный collectionView в UIViewController - IOS swift

Я пробовал много дней, чтобы понять это: enter image description here

Я хочу добавить в свой UIViewController два разных CollectionView. Например, я хочу поместить изображения в эти коллекции Каждый CollectionView использует свои собственные изображения. Возможно ли это?

Я буду очень рад, если кто-то может дать мне руку.:)

4b9b3361

Ответ 1

Это возможно, вам просто нужно добавить каждый UICollectionView в качестве подвью и установить делегат и dataSource в ваш UIViewController.

Вот краткий пример. Предполагая, что у вас есть один UICollectionView, вы должны иметь возможность адаптировать этот код к своим собственным потребностям, чтобы добавить вторую довольно легко:

let collectionViewA = UICollectionView()
let collectionViewB = UICollectionView()
let collectionViewAIdentifier = "CollectionViewACell"
let collectionViewBIdentifier = "CollectionViewBCell"

override func viewDidLoad() {
    // Initialize the collection views, set the desired frames
    collectionViewA.delegate = self
    collectionViewB.delegate = self

    collectionViewA.dataSource = self
    collectionViewB.dataSource = self

    self.view.addSubview(collectionViewA)
    self.view.addSubview(collectionViewB)
}

В функции делегата cellForItemAtIndexPath:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    if collectionView == self.collectionViewA {
        let cellA = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewAIdentifier) as UICollectionViewCell

        // Set up cell
        return cellA
    }

    else {
        let cellB = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewBIdentifier) as UICollectionViewCell

        // ...Set up cell

        return cellB
    }
}

В функции numberOfItemsInSection:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.collectionViewA {
        return 0 // Replace with count of your data for collectionViewA
    }

    return 0 // Replace with count of your data for collectionViewB
}

Ответ 2

Да - это вполне возможно. Вы можете либо присвоить их соответствующие UICollectionViewDelegates/UICollectionViewDataSources различным классам или подклассам CollectionViews, назначив как делегат, так и источник данных вашему текущему viewController и опустив ссылку на collectionView в методах делегирования следующим образом:

@IBOutlet collectionViewA: CustomCollectionViewA!
@IBOutlet collectionViewB: CustomCollectionViewB!


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    if let a = collectionView as? CustomCollectionViewA {
        return a.dequeueReusableCellWithIdentifier("reuseIdentifierA", forIndexPath: indexPath)
    } else {
        return collectionView.dequeueReusableCellWithIdentifier("reuseIdentifierB", forIndexPath: indexPath)    
    }
}

Ответ 3

создавать точки доступа для соответствующих просмотров коллекции: выходы:

@IBOutlet weak var collectionView: UICollectionView!

@IBOutlet weak var SecondCollectioView: UICollectionView!

метод:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as UICollectionViewCell

    if(collectionView == self.SecondCollectioView) {
        cell.backgroundColor = UIColor.black
    } else {
         cell.backgroundColor = self.randomColor()
    }

    return cell;
}

Это будет другим способом.

Ответ 4

Здесь моя рабочая версия для быстрого 4:

Этот код находится в отдельном вспомогательном файле:

import UIKit

class collectionViews {

static func collectionViewOne() -> UICollectionView {

    let layout = UICollectionViewFlowLayout()
    let collectionViewOne = UICollectionView(frame: CGRect(x: 0, y: 20, width: 200, height: 100), collectionViewLayout: layout)
    return collectionViewOne

}

static func collectionViewTwo() -> UICollectionView {

    let layout = UICollectionViewFlowLayout()
    let collectionViewTwo = UICollectionView(frame: CGRect(x: 0, y: 300, width: 200, height: 100), collectionViewLayout: layout)
    return collectionViewTwo

}


}

И вот код контроллера вида:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {


let collectionViewOne = collectionViews.collectionViewOne()
let collectionViewTwo = collectionViews.collectionViewTwo()

var myArray = ["1", "2"]
var myArray2 = ["3", "4"]

override func viewDidLoad() {
    super.viewDidLoad()


    collectionViewOne.delegate = self
    collectionViewOne.dataSource = self
    collectionViewOne.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    view.addSubview(collectionViewOne)


    collectionViewTwo.delegate = self
    collectionViewTwo.dataSource = self
    collectionViewTwo.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell2")
    view.addSubview(collectionViewTwo)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if collectionView == self.collectionViewOne {
        return myArray.count
    } else {
        return myArray2.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == self.collectionViewOne {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)

        myCell.backgroundColor = UIColor.red

        return myCell

    } else {

        let myCell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell2", for: indexPath as IndexPath)

        myCell2.backgroundColor = UIColor.blue

        return myCell2
    }

}


}

Результат