2016-12-26 95 views
2

我有疑問,在雨燕3.0選擇在雨燕3.0

在Objective-C,你可以聲明一個屬性selector這樣

@property (nonatomic,assign)SEL ItemSelected; 

但如何在雨燕3.0財產申報一個選擇,因爲我想在其他班級使用這個屬性,並且應該在該班級中採取行動。

我想使用這樣的(聲明中的tableview細胞):

var itemSelected = #selector(selctedItem(_ :)) 

在視圖 - 控制表視圖電池使用它

cell.itemSelected(target: self, action: HomeViewController.self.selctedItem(_ :)) 

它給錯誤

使用未申報項目selectedItem

我不知道如何在tableview中使用selctor。

回答

3

你可以像這樣在Swift 3中聲明選擇器。

var itemSelected: Selector? 

或者

var itemSelected = #selector(tapGesture) 

之後你可以使用上面itemSelected選擇用這樣的行動。

對於如:

let tap = UITapGestureRecognizer(target: self, action: itemSelected) 

而且tapGesture聲明如下

func tapGesture(_ sender: UITapGestureRecognizer) { } 

編輯:您已經添加collectionViewTableViewCell裏面,所以得到的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) 
    } 

} 

現在您的ViewController裏面,你已經添加的TableView實現協議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中。

func getIndexPathOfSelectedCell(tableIndexPath: IndexPath, collectionViewCell indexPath: IndexPath) { 
    print("TableView cell indexPath - \(tableIndexPath)") 
    print("CollectionView cell indexPath - \(indexPath)") 
} 
+0

如果我不喜歡把param ItemSelected給它的錯誤如未解析的標識符怎麼辦?如果我聲明var selector = #selector()它給出錯誤 – User

+0

@IOS_PROGRAMMER聲明它像第一個例如可選'var itemSelected:Selector?',後者設置它的值。 –

+0

如果我聲明它爲oprional,它告訴不能調用非函數類型 – User