我对 Swift 3.0 有疑问
在 Objective-C 中,您可以为 selector
声明一个属性,如下所示
@property (nonatomic,assign)SEL ItemSelected;
但是如何在 Swift 3.0 中将选择器声明为属性,因为我想在其他类中使用此属性,并且应该在该类中给出操作。
我尝试像这样使用它(在表格 View 单元格中声明):
var itemSelected = #selector(selctedItem(_ :))
在 View Controller TableView 单元格中使用它
cell.itemSelected(target: self, action: HomeViewController.self.selctedItem(_ :))
出现错误
use of Undeclared item selectedItem
我不知道如何在 tableview 中使用选择器。
最佳答案
您可以像这样在 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 ,声明一个协议(protocol)并将其与您的 tableViewCell 一起使用。
protocol SelectedCellDelegate {
func getIndexPathOfSelectedCell(tableIndexPath: IndexPath, collectionViewCell indexPath: IndexPath)
}
现在创建一个 SelectedCellDelegate 实例和 IndexPath
实例在您的 CustomTableViewCell 中。
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 中实现协议(protocol) SelectedCellDelegate
并设置delegate
和tableCellIndexPath
在cellForRowAt indexPath
方法。
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 中添加委托(delegate)方法。
func getIndexPathOfSelectedCell(tableIndexPath: IndexPath, collectionViewCell indexPath: IndexPath) {
print("TableView cell indexPath - \(tableIndexPath)")
print("CollectionView cell indexPath - \(indexPath)")
}
关于ios - Swift 3.0 中的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41327152/