gpt4 book ai didi

ios - 控制两个不同的collectionview

转载 作者:行者123 更新时间:2023-12-01 21:38:38 27 4
gpt4 key购买 nike

我目前正在尝试控制两个不同的 Collection View 。我还在每个 Collection View 中嵌入了按钮,我想让它们中的每一个都包含一组来自数组的值。到目前为止,这是我的代码,我不知道我应该做些什么来实现这一点:

import UIKit
class MyButtonCell: UICollectionViewCell{
@IBOutlet weak var buttonOne: UIButton!
@IBOutlet weak var targetButton: UIButton!

var callback: (() -> ())?

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

}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
contentView.layer.borderWidth = 1
contentView.layer.borderColor = UIColor.black.cgColor
}

@IBAction func buttonTapped(_ sender: UIButton) {
callback?()
}
}

class StevenViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

let buttonTitles: [String] = [
"4", "6", "7", "8"
]

var targetButtonTitles: [String] = [
"", "", "", ""
]

var current:String = ""
@IBOutlet var collectionView: UICollectionView!

@IBOutlet var targetCollection: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()
targetCollection.delegate = self
targetCollection.dataSource = self

collectionView.delegate = self
collectionView.dataSource = self


}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return buttonTitles.count

}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell

// set the button title (and any other properties)

cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])


targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])

// set the cell's callback closure
cell.callback = {
print("Button was tapped at \(indexPath)")
self.targetButtonTitles.append(self.buttonTitles[indexPath.item])
print(self.targetButtonTitles)


// do what you want when the button is tapped
}


return targetCell

}
}
buttonTitles 和 targetButtonTitles 是我希望每个 collectionview 包含的两个数组。
这就是它现在的样子 - 两者都显示相同的数组。我知道我可能应该为单元格设置不同的标识符 ID,但是一旦我这样做了,它就会给我一个错误,说“无法使一种 View 出列:带有标识符目标的 UICollectionElementKindCell”
enter image description here

最佳答案

在 UICollectionViewDelegate & UICollectionViewDataSource
您可以使用此代码片段来识别当前的 UICollectionView。

 if collectionView == [YOUR_COLLECTIONVIEW_QUTLET] {


}

关于ios - 控制两个不同的collectionview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62622257/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com