简体   繁体   English

如何根据用户选择在CollectionView标题下显示不同的单元格?

[英]How to display different cells below CollectionView header depending on users selection?

EDIT: I am trying to re-create the instagram/twitter profile page. 编辑:我正在尝试重新创建instagram / twitter个人资料页面。 So if the current way I am trying to do it won't work, feel free to tell me how to recreate these profile pages in a totally different way. 因此,如果我尝试这样做的当前方式不起作用,请随时告诉我如何以完全不同的方式重新创建这些配置文件页面。

I have set up a UICollectionView with a header. 我已经设置了一个带标题的UICollectionView。 Inside this header, there is a menuBar that has two different selection options. 在这个标题内,有一个menuBar有两个不同的选择选项。 If the user selects the first index, the menuBar returns 0. If the user selects the second index, the menuBar returns 1. 如果用户选择第一个索引,则menuBar返回0.如果用户选择第二个索引,则menuBar返回1。

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

            return cell
        }

Here is a picture of the menu bar and the collectionview cells below it: 这是菜单栏和它下面的collectionview单元格的图片: 在此输入图像描述

I also have this code to set up the cells: 我也有这个代码来设置单元格:

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let menuBarIndex = profileMenuBarSelectionIndex.menuBarIndexSelection
            var cell: UICollectionViewCell
            switch menuBarIndex {
            case 0:
               cell = collectionView.dequeueReusableCell(withReuseIdentifier: test1CellId, for: indexPath) as! test1Cell
            case 1:
               cell = collectionView.dequeueReusableCell(withReuseIdentifier: test2CellId, for: indexPath) as! test2Cell
            default:
               cell = collectionView.dequeueReusableCell(withReuseIdentifier: test3CellId, for: indexPath) as! test3Cell
            }
            return cell
        }

EDIT 2: I have now added this code, where myTestAction is the delegate function of testAction in a different file. 编辑2:我现在添加了这段代码,其中myTestAction是另一个文件中testAction的委托函数。

var index: Int = 0
func testAction() {
    index = index == 1 ? 0 : 1
    collectionView.reloadData()
}

func myTestAction() {
    delegate?.testAction()
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    switch indexPath.row{
    case 0:
        menuBarIndexSelection = 0
        menuBarIndexChangeFlag = 1
    case 1:
        menuBarIndexSelection = 1
        menuBarIndexChangeFlag = 2
    case 2:
        menuBarIndexSelection = 2
        menuBarIndexChangeFlag = 3
    default:
        menuBarIndexSelection = 0
    }
    myTestAction()
}

I want to be able to display different cells below the header depending on which value menuBar returns. 我希望能够在标题下方显示不同的单元格,具体取决于menuBar返回的值。 How would I do this? 我该怎么做? OR How can I recreate the Instagram profile page? 或者如何重新创建Instagram个人资料页面?

Put a check on cellForRow and supplimentaryViewsForHeader for menuBar value. 检查cellForRow和suppviewsViewsForHeader以获取menuBar值。 And when the value of menuBar changes just reload the table. 当menuBar的值改变时,只需重新加载表。 At the time of reloading the data will be shown according to your check present in dataSources. 在重新加载时,将根据dataSources中的检查显示数据。

// MENU BAR BUTTON CLICK // MENU BAR按钮点击

self.collectionView.reloadData()

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
     if menuBar == 0 {
     // show this image
     }else{
     //show that image
     }
        return cell
    }

Try this, 尝试这个,

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

//Take a variable menuBar. when the user tap change it's value to 0 or 1  and reload collection view when user tap on menu button.

    if menuBar == 0 {
      return 0
    }else{
      return 1
    }

The reason for getting the compiler error you describe is that you create 4 different variables called "cell": 获取您描述的编译器错误的原因是您创建了4个名为“cell”的不同变量:

var cell: UICollectionViewCell
switch menuBarIndex {
case 0:
    var cell = ...
case 1:
    var cell = ...
default:
    var cell = ...
}
return cell

The cell instance you return at the end of the function was never assigned a value. 您在函数末尾返回的单元格实例从未分配过值。 Assigning the first cell variable instead of creating new ones in each case should fix the compiler error: 在每种情况下分配第一个单元格变量而不是创建新的单元格应该修复编译器错误:

var cell: UICollectionViewCell
switch menuBarIndex {
case 0:
    cell = collectionView.dequeueReusableCell(withReuseIdentifier: test1CellId, for: indexPath) as! test1Cell
case 1:
    cell = collectionView.dequeueReusableCell(withReuseIdentifier: test2CellId, for: indexPath) as! test2Cell
default:
    cell = collectionView.dequeueReusableCell(withReuseIdentifier: test3CellId, for: indexPath) as! test3Cell
}
return cell

------------------------- EDIT --------------------- -------------------------编辑---------------------

The answer above fixed the compiler error but not the actual question. 上面的答案修复了编译器错误,但没有解决实际问题。 I created a small sample project that does what is needed and works fine. 我创建了一个小样本项目,可以完成所需的工作并且工作正常。 Maybe that helps with figuring out the problem. 也许这有助于找出问题所在。 I just created a single view application in Xcode, this is the code for the one view controller in the project and the cells: 我刚刚在Xcode中创建了一个视图应用程序,这是项目中单个视图控制器和单元格的代码:

class ViewController: UIViewController, UICollectionViewDataSource {

    var index: Int = 0
    var collectionView: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 200, height: 50))
        btn.backgroundColor = .green
        btn.setTitle("Change cell color", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.addTarget(self, action: #selector(testAction), for: .touchUpInside)
        view.addSubview(btn)

        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 60, width: view.frame.width, height: view.frame.height - 60), collectionViewLayout: layout)
        collectionView?.backgroundColor = .white
        collectionView?.dataSource = self
        collectionView?.register(RedCell.self, forCellWithReuseIdentifier: "red")
        collectionView?.register(BlueCell.self, forCellWithReuseIdentifier: "blue")
        view.addSubview(collectionView!)
    }

    func testAction() {
        index = index == 1 ? 0 : 1
        collectionView?.reloadData()
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell: UICollectionViewCell
        switch index {
        case 0:
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "red", for: indexPath)
        case 1:
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "blue", for: indexPath)
        default:
            cell = UICollectionViewCell()
        }
        return cell
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        return CGSize(width: 50, height: 50)
    }
}

class RedCell: UICollectionViewCell {

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

        backgroundColor = .red
    }

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

class BlueCell: UICollectionViewCell {

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

        backgroundColor = .blue
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 CollectionView 中只显示 5 个单元格? - How to display only 5 cells in CollectionView? 集合查看不同的单元格选择 - CollectionView different cell selection 多个tableview单元格内的collectionview,如何处理选择? - Collectionview inside multiple tableview cells, how to handle selection? 重新加载collectionview单元格而不是节标题 - Reload collectionview cells and not the section header 如何在 Collectionview Swift 中水平显示特定部分单元格/项目 - How to display particular section cells/items in centre horizontally in Collectionview Swift Collectionview单元格上的不同背景颜色 - Collectionview different background colors on cells iOS:如何创建具有不同大小和可点击单元格的 collectionView - iOS: How to create a collectionView with different size & clickable cells 如何根据通过表视图的选择在uiview中显示不同的视图控制器(请参见说明中的图像)? - How do I display different view controllers in a uiview depending on selection through a tableview (Please see the image in description)? 如何在collectionView自定义布局中的其他补充标题单元格上方添加标题补充单元格 - How to add a header supplementary cell above other supplementary header cells In a collectionView custom layout 如何正确对齐这些 collectionview 单元格? - How to align these collectionview cells properly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM