【发布时间】:2020-10-18 16:18:39
【问题描述】:
我目前正在尝试控制两个不同的集合视图。我还在每个集合视图中嵌入了按钮,我想让它们中的每一个都包含一组来自数组的值。到目前为止,这是我的代码,我不知道我应该做些什么来实现它:
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”
【问题讨论】:
标签: ios swift xcode button uicollectionview