我有一个 tableview 单元格,我在其中添加了 collectionview 单元格(用于水平滚动)。
现在我想在水平 collectionview 的任何单元格的按钮上推送到其他导航 Controller 。怎么做 ?啊
代码:
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
现在我们要调用闭包
如下实现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
}
希望对你有帮助
关于ios - 将目标添加到 tableview 单元格内的 collectionview 单元格的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104671/