【发布时间】:2018-01-28 12:01:37
【问题描述】:
在我的 viewController 中,我有 tableView 和 collectionView。
当我点击 中的 不同行 时,我尝试在 collectionView 中显示 不同的数组表视图。
所以当我点击 tableView 中的 firstRow 时,我想在 collectionView 中显示 firstArray,当我点击 tableView 中的 secondRow,我想在 collectionView 中显示 secondArray,当我点击 thirdRow 在 tableView 中,我想在 collectionView 中显示 thirdArray。
我该怎么做?
我的测试代码:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var tableView: UITableView!
var tableArray: [String] = ["1", "2", "3"]
var secondArray: [String] = ["One", "Two"]
var thirdArray: [String] = ["Three", "Four"]
var fourthArray: [String] = ["Five", "Six"]
// TABLEVIEW
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableCell
cell.tableLabel.text = tableArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
// COLLECTIONVIEW
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return secondArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CollectionCell
cell.collectionLabel.text = secondArray[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath)
}
}
class TableCell: UITableViewCell {
@IBOutlet weak var tableLabel: UILabel!
}
class CollectionCell: UICollectionViewCell {
@IBOutlet weak var collectionLabel: UILabel!
}
我明白了if需要使用什么条件,但是如何正确使用呢?
【问题讨论】:
-
我建议使用
var collectionArray,它可以用于您的UICollectionView。在tableView(_:didSelectRowAt:):if indexPath.row == 0 { collectionArray = secondArray} else if indexPath.row == 1 { collectionArray = thirdArray}... collectionView.reloadData()
标签: ios swift xcode uitableview uicollectionview