【发布时间】:2020-04-10 14:37:02
【问题描述】:
首先,很抱歉,我英语不好。
无论如何,当我单击 UICollectionView 外部的 UIButton 时,我想选择 UICollectionViewCell 中的所有单元格。但我不知道该怎么办。
我认为使用 UIButton 的集合(如 5 星)是可能的。我只是试试看。
好吧..点击下面的按钮。蓝色的单元格是错误的。
如果您单击“每天”按钮,所有单元格将变为红色。红色的单元格表示它被选中。
如果您单击“周末”按钮,最右边的两个单元格将变为红色。现在你知道这个 UICollectionView 的意思是“一周”。 so, when 'Weekend' is selected, other 5 days will be blue.
我用 UICollectionView 做的。但我不知道我如何用外面的按钮控制。如果您需要更多信息和代码,或者您不明白我会编辑它或发表评论。请告诉我怎么做。
关于 UIButton 和 UICollectionView 的 ViewController 代码在这里。并且 CollectionViewCell 中有一个 imageview ......就是这样......
import UIKit
class CreateViewController: UIViewController {
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var MotivTextField: UITextField!
@IBOutlet weak var repeatCollectionView: UICollectionView!
@IBAction func everydayBtn(_ sender: Any) {
// empty
}
@IBAction func weekdayBtn(_ sender: Any) {
// empty
}
@IBAction func weekendBtn(_ sender: Any) {
// empty
}
var selectedDay = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0...7 {
self.selectedDay.append(false)
}
repeatCollectionView.delegate = self
repeatCollectionView.dataSource = self
repeatCollectionView.isScrollEnabled = false
}
}
extension CreateViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? RepeatDayCVCell {
cell.dayBtn.backgroundColor = UIColor.red
}
}
}
extension CreateViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RepeatDayCVCell", for: indexPath) as! RepeatDayCVCell
if self.selectedDay[indexPath.row] == true {
cell.dayBtn.backgroundColor = UIColor.red
}
else {
cell.dayBtn.backgroundColor = UIColor.blue
}
return cell
}
}
【问题讨论】:
-
嗨@doori,首先您需要根据您的需要设置您选择的单元格。所以,你需要设置单元格被选中,而其他单元格没有被选中。你明白?所以,当你点击一个按钮时,你需要设置你的数组(只有你需要选择的值)并重新加载你的表格视图,然后验证是否被选中并更改颜色或任何你想要的。明白了吗?
-
@DanielArantesLoverde 谢谢!您的详细解释我完全理解。
-
谢谢!很高兴能帮到你!
标签: ios swift xcode collectionview