Обновление содержимого ячейки в UICollection2 из UICollection 1 - PullRequest
0 голосов
/ 04 декабря 2018

У меня есть 3 UICollections.Основная коллекция UICollection, содержащая 2 ячейки, каждая из которых содержит коллекцию пользовательского интерфейса.

В первой ячейке из основной коллекции UIC загружается вертикальная коллекция с 3 ячейками.

Во второй ячейке из основной коллекции UIC создается представление одной ячейки.

enter image description here

См. Изображение выше: основной UICollectionView представлен желтым цветом, каждая из двух ячеек представлена ​​красным и синим цветом соответственно.

Первая ячейка (из основного вида коллекции) содержит коллекцию из 3 клеток (красная).Я хочу обновить синюю ячейку представления uicollection, когда я щелкаю (нажимаю) на любую (из 3) ячейку, расположенную в красной uicollection.

FullScreenImage.swift

class FullScreenImage: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{



let bottomUIColletion: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.scrollDirection = .horizontal
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return cv
}()


let bottomContentCell = "buttonContentCell"
let bottomButtonsCell = "buttonButtonsCell"



override func viewDidLoad() {
    super.viewDidLoad()
    self.bottomUIColletion.delegate = self
    self.bottomUIColletion.dataSource = self
    self.bottomUIColletion.register(BottomButtonsCollectionViewCell.self, forCellWithReuseIdentifier: bottomButtonsCell)
    self.bottomUIColletion.register(BottomContentCollectionViewCell.self, forCellWithReuseIdentifier: bottomContentCell)

    self.bottomUIColletion.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(self.bottomUIColletion)

    DispatchQueue.main.async {

        self.bottomUIColletion.topAnchor.constraint(equalTo: self.bottomView.topAnchor, constant: 0).isActive = true
        self.bottomUIColletion.leadingAnchor.constraint(equalTo: self.bottomView.leadingAnchor, constant: 0).isActive = true
        self.bottomUIColletion.trailingAnchor.constraint(equalTo: self.bottomView.trailingAnchor, constant: 0).isActive = true
        self.bottomUIColletion.heightAnchor.constraint(equalToConstant: self.bottomView.frame.height).isActive = true


    }


}

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

    return 2
}



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

    if indexPath.row == 0{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: bottomButtonsCell, for: indexPath) as! BottomButtonsCollectionViewCell
        return cell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: bottomContentCell, for: indexPath) as! BottomContentCollectionViewCell

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if indexPath.row == 0 {
        return CGSize(width: 50, height: self.bottomUIColletion.frame.height)
    }

    return CGSize(width: self.bottomUIColletion.frame.width-50, height: self.bottomUIColletion.frame.height)
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}




}

BottomButtonsCollectionViewCell.swift

import UIKit
import FontAwesome_swift

class BottomButtonsCollectionViewCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let parentCollection = FullScreenImage()
let otherController = BottomContentCollectionViewCell()

let buttonCollection: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.scrollDirection = .vertical
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.clear
    return cv
}()

let buttonCell = "buttonCell"

func setup(){

    buttonCollection.delegate = self
    buttonCollection.dataSource = self

    buttonCollection.register(ButtonLayout.self, forCellWithReuseIdentifier: buttonCell)

    buttonCollection.translatesAutoresizingMaskIntoConstraints = false

    addSubview(buttonCollection)

    buttonCollection.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
    buttonCollection.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
    buttonCollection.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
    buttonCollection.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true


 }

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: buttonCell, for: indexPath) as! ButtonLayout
    if indexPath.row == 0{
        cell.actionBtn.setImage(UIImage(named: "font_size_icon_white"), for: .normal)
    }else if indexPath.row == 1{
        cell.actionBtn.titleLabel?.font = UIFont.fontAwesome(ofSize: 25, style: .solid )
        cell.actionBtn.setTitle(String.fontAwesomeIcon(name: .font), for: .normal)
    }else if indexPath.row == 2{
        cell.actionBtn.titleLabel?.font = UIFont.fontAwesome(ofSize: 25, style: .solid )
        cell.actionBtn.setTitle(String.fontAwesomeIcon(name: .palette), for: .normal)
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.frame.width, height: self.frame.height / 3)
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {



    otherController.btnSelected = indexPath.row
        parentCollection.bottomUIColletion.reloadItems(at: parentCollection.bottomUIColletion.indexPathsForVisibleItems)




    parentCollection.bottomUIColletion.reloadData()
    parentCollection.bottomUIColletion.layoutIfNeeded()
    //parentCollection.bottomUIColletion.





}

} ​​

class ButtonLayout: UICollectionViewCell{
override init(frame: CGRect) {
    super.init(frame:frame)
    setupCell()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let actionBtn = UIButton()


func setupCell(){
    backgroundColor = UIColor.darkGray
    actionBtn.translatesAutoresizingMaskIntoConstraints = false
    addSubview(actionBtn)

    actionBtn.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 10).isActive = true
    actionBtn.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
    actionBtn.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
    actionBtn.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true

 }

}

BottomContentCollectionViewCell.swift

import UIKit

class BottomContentCollectionViewCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{

var btnSelected = Int()

let contentCollection: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.scrollDirection = .vertical
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.clear
    return cv
}()

let textCell = "textSizeCell"
let fontTypeCell = "fontCell"
let backgroundColorCell = "backgroundCell"
let defaultCellLayout = "defaultCellLayout"


override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}



func setup(){

    contentCollection.delegate = self
    contentCollection.dataSource = self

    contentCollection.register(textSizeCell.self, forCellWithReuseIdentifier: textCell)
    contentCollection.register(fontCell.self, forCellWithReuseIdentifier: fontTypeCell)
    contentCollection.register(BackgroundContentCollectionViewCell.self, forCellWithReuseIdentifier: backgroundColorCell)
    contentCollection.register(defaultCell.self, forCellWithReuseIdentifier: defaultCellLayout)

    contentCollection.translatesAutoresizingMaskIntoConstraints = false

    addSubview(contentCollection)

    contentCollection.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
    contentCollection.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
    contentCollection.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
    contentCollection.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true

}


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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    print("Button Content Collection: \(btnSelected)")

    //var cell = UICollectionViewCell()

    switch btnSelected {
    case 0:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: textCell, for: indexPath) as! textSizeCell
        print("I was called: textSizeCell viewcell")
        return cell

    case 1:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: fontTypeCell, for: indexPath) as! fontCell
        cell.nameLabel.text = "Awe"
        print("I was called: fontcell viewcell")
        return cell

    case 2:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: backgroundColorCell, for: indexPath) as! BackgroundContentCollectionViewCell
        print("I was called: backgroundCell viewcell")
        return cell

    default:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: defaultCellLayout, for: indexPath) as! defaultCell
        print("I was called: defaultCell viewcell")
        return cell
    }


}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.frame.width, height: self.frame.height)
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}


}

class textSizeCell: UICollectionViewCell{
override init(frame: CGRect) {
    super.init(frame:frame)
    setupCell()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func prepareForReuse() {
    super.prepareForReuse()
}

func setupCell(){
    backgroundColor = UIColor.purple
     print("textSizeCell called.")
}
}

class fontCell: UICollectionViewCell{
override init(frame: CGRect) {
    super.init(frame:frame)
    setupCell()
}

override func prepareForReuse() {
    super.prepareForReuse()

}

let nameLabel: UILabel = {
    let label  = UILabel()
    label.textAlignment = .center
    //label.adjustsFontSizeToFitWidth = true
    //label.minimumScaleFactor = 0.5
    label.font = label.font.withSize(10)
    label.textColor = UIColor.lightGray
    label.numberOfLines = 0
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}



func setupCell(){
    self.backgroundColor = UIColor.yellow
    addSubview(nameLabel)
    nameLabel.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor, constant: 0).isActive = true
    nameLabel.centerYAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerYAnchor, constant: 0).isActive = true
    nameLabel.heightAnchor.constraint(equalToConstant: 40)
    print("Font Cell setupCell called.")

}
}



class defaultCell: UICollectionViewCell{
override init(frame: CGRect) {
    super.init(frame:frame)
    setupCell()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func prepareForReuse() {
    super.prepareForReuse()
}

func setupCell(){
    backgroundColor = UIColor.white


}
}

Я пытался перезагрузить содержимое ячейки на основеячейка выбрана в didSelectItemAt в BottomButtonsCollectionViewCell.swift, а затем перезагрузка данных, но мне не повезло.При запуске приложения перезагрузка не происходит.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {



    otherController.btnSelected = indexPath.row
        parentCollection.bottomUIColletion.reloadItems(at: parentCollection.bottomUIColletion.indexPathsForVisibleItems)




    parentCollection.bottomUIColletion.reloadData()
    parentCollection.bottomUIColletion.layoutIfNeeded()
    //parentCollection.bottomUIColletion.





}

Я что-то пропустил?Я работаю над этим в течение 2 дней, и я чувствую себя подавленным и немного расстроенным.Кроме того, я мог пропустить любой подобный вопрос в SO.Если это так, пожалуйста, укажите мне в правильном направлении.

Я действительно надеюсь, что объяснил здесь.Спасибо за ваш вклад.

1 Ответ

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

Вы создаете делегат с именем RedCollectionViewDelegate, в котором будет определена функция didSelect (ячейка).

определяет переменную weak var delegate : RedCollectionViewDelegate в вашем RedCollectionView

Когда вы настраиваете основной вид коллекции, у вас будет доступ как к RedCollectionView, так и к BlueCollectionView. Сделайте делегат либо основным collectionViewView, либо BlueCollection.или оба ... это действительно зависит от вас.

Затем определите функцию и делайте что хотите.

...