ios - Swift 3.0 中的选择器

标签 ios swift swift3 performselector

我对 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并设置delegatetableCellIndexPathcellForRowAt 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/

相关文章:

ios - iOS 上的 CloudKit 无法获取我想要的所有记录

ios - ABPeoplePickerNavigationController 类不支持子类化

ios - 使用 UINavigationController 作为内部 UIView

ios - 将 View 动画化到 collectionView 中的选定单元格或 scrollView 中的 tableView

swift - swift 中的属性文本与行对齐

ios - 如何在可缩放 ScrollView 中绘制可点击的网格对象从远程 json 数据中获取数据?

ios - 从入门/教程屏幕执行 segue

ios - tableView 滚动到底部不显示最后一部分,必须手动滚动,有人知道吗?

iphone - 提交 iphone 应用程序时遇到问题

Swift:如何在向 Firebase 变量添加值时修复无限循环