[英]Button add target function not called in CollectionView cell
[英]Add target to button of collectionview cell inside tableview cell
我有一個tableview單元格,其中添加了collectionview單元格(用於水平滾動)。
現在,我想在水平collectionview的任何單元格的按鈕上按下其他導航控制器。 怎么做 ? Ø
代碼:
ViewController.swift:
class ViewController: UIViewController {
var categories = ["Action", "Drama", "Science Fiction", "Kids", "Horror"]
}
extension ViewController : UITableViewDelegate { }
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categories[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoryRow
return cell
}
}
CategoryRow.swift
class CategoryRow : UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
}
extension CategoryRow : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! VideoCell
cell.button.addTarget(self, action:#selector(ViewController.goToLookAtPage(_:)), for: .touchUpInside)
return cell
}
}
extension CategoryRow : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow:CGFloat = 4
let hardCodedPadding:CGFloat = 5
let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
let itemHeight = collectionView.bounds.height - (2 * hardCodedPadding)
return CGSize(width: itemWidth, height: itemHeight)
}
}
我在哪里聲明goToLookAtPage函數?
VideoCell.swift
class VideoCell : UICollectionViewCell {
@IBOutlet weak var button: UIButton!
}
您需要在CategoryRow
類上進行聲明,還需要聲明全局關閉
喜歡
var buttonTapped:((CategoryRow?) -> Void)? = nil
現在我們可以closure
如下實現goToLookAtPage
func goToLookAtPage(_ sender:UIButton) {
if let btnAction = self.buttonTapped {
btnAction(self)
}
}
現在在您的ViewController
在cellForRowAtIndexPath
添加以下內容
cell.buttonTapped = {(cell) -> Void in
//You Got your response , do push in main Thread
}
希望對您有幫助
在按鈕處理程序函數中,獲取按鈕的位置,其中發送者是您的按鈕。
let position = sender.convert(CGPoint.zero, to: self.collectionView)
獲取給定位置的索引路徑。
let indexPath = self.collectionView?.indexPathForItem(at: position)
使用索引路徑從數據源中獲取模型。
let model = self.data[indexPath.row]
現在您已經有了數據模型,將其傳遞到目的地並推送視圖控制器或其他任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.