我有两个CollectionView在.ViewController,如何更改CollectionView_2_items项数据时,立即选择CollectionView_1_types牢房?
我的结构是:
struct MyObj {
var type: String
var items:[String]
}
let a = Myobj(type: "food", items:["apple", "ham", "egg"])
let b = Myobj(type: "color", items:["white", "black", "yellow"])
var Allobj:[Myobj] = [a, b]```
我想展示并更改Myobj.项目CollectionView_2_item当我改变Myobj.type在……里面CollectionView_1_types.
以下是我在ViewController中的代码:
class MainControllerView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var TypeCollectionView: UICollectionView!
@IBOutlet weak var itemCollectionView: UICollectionView!
struct MyObj {
var item: String = ""
var Allitems: [String] = []
}
var Allobj:[Myobj] = []
var ary:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.TypeCollectionView.delegate = self
self.TypeCollectionView.dataSource = self
self.itemCollectionView.delegate = self
self.itemCollectionView.dataSource = self
let a = MyItem(item: "food", Allitems: ["apple", "ham", "egg"])
let b = MyItem(item: "color", Allitems: ["white", "black", "yellow"])
Allobj = [a, b]
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == TypeCollectionView {
return Allobj.count
}else if collectionView == itemCollectionView {
return ary.count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPath) as UICollectionViewCell
if collectionView == TypeCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TypeCollectionCell
let d = Allobj[indexPath.row]
cell.typeLabel.text = d.item
return cell
}else if collectionView == itemCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! itemsCollectionCell
let d = ary[indexPath.row]
cell.itemLabel.text = d
return cell
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let d = Allobj[indexPath.row]
if collectionView == TypeCollectionView {
ary = d.Allitems
}
}
}
如果您已经以标准的方式实现了集合视图,这应该是非常简单的。
将呈现视图控制器与UICollectionViewDelegate相一致,将收藏品视图1的委托设置为视图控制器,并实现collectionView(_:didSelectItemAt:)委托方法在这个委托方法中,加载您喜欢的任何数据。
extension myViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
getCV2Data(using: indexpath)() //use the collectionView's indexPath properties to prepare whatever data you need for collectionView2
collectionView2.reloadData
}
}
哪里getCV2Datat(using:)是一种方法,它设置必要的数据(如果需要的话),以便当‘corctionView 2’重新丢失它的数据时,它得到相关的和最近的数据。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。