我目前正在尝试控制两个不同的集合视图。我还在每个集合视图中都嵌入了按钮,我希望它们每个都包含来自数组的一组值。到目前为止,这是我的代码,我不知道该怎么做:
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,但是一旦这样做,它给我一个错误,提示“无法使种类的视图出列:具有标识符目标的UICollectionElementKindCell”
在UICollectionViewDelegate和UICollectionViewDataSource中
您可以使用此代码段来标识当前的UICollectionView。
if collectionView == [YOUR_COLLECTIONVIEW_QUTLET] {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句