【发布时间】:2020-10-18 17:38:33
【问题描述】:
我目前有两个collectionview,每个都与一个字符串数组链接,并嵌入了按钮。我想这样做,以便我可以在底部的 collectionview 上选择一个值,然后能够将该值放到顶部的 collectionview 上的一个位置,再次点击它。我不确定每次点击按钮时如何更新集合视图。
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)
if collectionView == self.collectionView {
// Setup here your cell
cell.callback = {
print("Button was tapped at \(indexPath)")
self.targetButtonTitles[indexPath.item] = self.buttonTitles[indexPath.item]
//print(self.targetButtonTitles)
self.current = self.buttonTitles[indexPath.item]
print(self.current)
// do what you want when the button is tapped
}
cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])
return cell
} else {
// Setup here your targetCell
cell.callback = {
if self.current != ""{
self.targetButtonTitles[indexPath.item] = self.current
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
}
}
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
return targetCell
}
}
}
我不确定如何将“返回目标单元”放入 cell.callback 或 iBaction 中
【问题讨论】:
标签: ios swift xcode button uicollectionview