【发布时间】:2020-07-07 10:14:56
【问题描述】:
我想知道如何显示表视图和集合视图索引的索引路径。在我的情况下,表格视图单元格包含许多集合视图单元格。并且集合视图单元格包含一个按钮,当用户按下此按钮时,会显示一个警报显示,该按钮显示来自表视图索引(即 2)和集合视图索引(即 4)的按下按钮。
这是怎么做到的?
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK:- Tabel View
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellForTableView
return cell
}
//MARK:- Collectio View
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CellForCollectionView
cell.myIndexPath = indexPath
cell.TabedDelegate = self
return cell
}
}
extension ViewController : collectionViewCellTabbedDelegate{
func clickBtnTabbed(indexPath: IndexPath) {
print(indexPath)
let alert = UIAlertController(title: "Show Index Number!", message: "Selected Collection View Index Number is \(indexPath[1])", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
这是我的收藏视图单元格:
import UIKit
protocol collectionViewCellTabbedDelegate {
func clickBtnTabbed(indexPath: IndexPath)
}
class CellForCollectionView: UICollectionViewCell {
var myIndexPath : IndexPath!
var TabedDelegate : collectionViewCellTabbedDelegate?
@IBOutlet weak var clickBtnOut: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.clickBtnOut.addTarget(self, action: #selector(clickBtnAct(_:)), for: .touchUpInside)
}
@IBAction func clickBtnAct(_ sender: Any) {
TabedDelegate?.clickBtnTabbed(indexPath: self.myIndexPath)
}
}
【问题讨论】:
-
拜托,Stackoverflow 不是代码编写服务。显示您目前拥有的代码。
-
@vadian 现在请给我正确的解决方案
标签: ios swift uitableview uicollectionview