【发布时间】:2020-10-18 14:11:19
【问题描述】:
我正在尝试实现一个功能,即每当我从底部的集合视图中点击一个按钮时,被点击的特定值将反映在中间的集合视图上。到目前为止,我已经实现了底部的 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,UICollectionViewDelegateFlowLayout {
let buttonTitles: [String] = [
"4", "6", "7", "8"
]
var targetButtonTitles: [String] = []
//number array
@IBOutlet var collectionView: UICollectionView!
@IBOutlet weak var targetCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
targetCollection.delegate = self
targetCollection.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: "target", for: indexPath) as! MyButtonCell
// set the button title (and any other properties)
cell.buttonOne.setTitle(buttonTitles[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)
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
// do what you want when the button is tapped
}
return cell
}
}
我的故事板:
模拟器中显示的内容:
【问题讨论】:
-
我看不到您在哪里重新加载收藏视图。
标签: ios swift xcode button uicollectionview