你可以像这样在 Swift 3 中声明选择器。
var itemSelected: Selector?
或者
var itemSelected = #selector(tapGesture)
稍后您可以使用上面的itemSelected 选择器进行这样的操作。
例如:
let tap = UITapGestureRecognizer(target: self, action: itemSelected)
tapGesture 声明为
func tapGesture(_ sender: UITapGestureRecognizer) { }
编辑:您已将collectionView 添加到您的TableViewCell 中,因此要获得CollectionViewCell 的选定IndexPath,请声明一个协议并将其与您的tableViewCell 一起使用。
protocol SelectedCellDelegate {
func getIndexPathOfSelectedCell(tableIndexPath: IndexPath, collectionViewCell indexPath: IndexPath)
}
现在在您的 CustomTableViewCell 中创建一个 SelectedCellDelegate 实例和一个 IndexPath 实例。
class CustomTableCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
//All outlet
var delegate: SelectedCellDelegate?
var tableCellIndexPath = IndexPath()
//CollectionViewDataSource method
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate?.getIndexPathOfSelectedCell(tableIndexPath: tableCellIndexPath, indexPath: indexPath)
}
}
现在在添加 TableView 的 ViewController 中实现协议 SelectedCellDelegate 并在 cellForRowAt indexPath 方法中设置 delegate 和 tableCellIndexPath。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SelectedCellDelegate {
//your methods
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell // Initialize the cell with your custom TableCell
cell.delegate = self
cell.tableCellIndexPath = indexPath
return cell
}
现在在您的 ViewController 中添加委托方法。
func getIndexPathOfSelectedCell(tableIndexPath: IndexPath, collectionViewCell indexPath: IndexPath) {
print("TableView cell indexPath - \(tableIndexPath)")
print("CollectionView cell indexPath - \(indexPath)")
}