[英]How to get UITableView row when user taps on UICollectionViewCell
應用方案-
正如你從我的 App Scheme 中看到的,我有UITableView
並且在UITableViewCells
里面我有UICollectionView
。
我現在的問題是如何在用戶點擊UICollectionViewCell
時獲取UITableView
行?
我試過這個,但這對我不起作用:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
let main = ViewController()
if let tableViewcell = superview?.superview as? ExploreTableViewCell {
let indexPath = main.tableView.indexPath(for: tableViewcell)
print(indexPath)
}
}
為了擴展 Subramanian Mariappan 的概念並使用delegate
模式在UIViewController
了解集合視圖單元格中的選擇,請在https://github.com/sauvikapple/StackoverflowQ63802523檢查您的解決方案。
重構這個 viewController 在我的待辦事項列表中,但這應該會有所幫助。
關鍵是setCollectionViewDataSourceDelegate()
內willDisplayCell()
這讓您可以點擊單元格和 collectionView。 您可以執行一些操作,例如將標記設置為行號。
表視圖單元格:
import UIKit
class CollectionViewInsideTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "cellNibName", bundle: nil), forCellWithReuseIdentifier: "cellIdentifier")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forSection section: Int, multipleSelection: Bool) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.allowsSelection = true // If Needed
collectionView.allowsMultipleSelection = multipleSelection // If Needed
collectionView.scrollToItem(at: IndexPath(item: 31, section: 0), at: .right, animated: false)
self.collectionView.layoutSubviews()
}
}
執行:
cellforRow() {
let collectionCell = CollectionViewInsideTableViewCell // ETC
return collectionCell
}
extension TableViewController: UICollectionViewDelegate, UICollectionViewDataSource {
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? CollectionViewInsideTableViewCell else { return }
tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forSection: indexPath.section, multipleSelection: true)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CollectionViewCell // ETC
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.