如何在选择 tableView 的行单元格时显示视图控制器(作为集合视图单元格)? [英] How to show view controller on selecting row cell of tableView(as a collection view cell)?

查看:25
本文介绍了如何在选择 tableView 的行单元格时显示视图控制器(作为集合视图单元格)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主视图控制器,它有一个集合视图,它的集合视图单元格每个都初始化为一个 tableView,以在该集合视图单元格内提供多行服务.如果您感到困惑,下面是当前状态的快照.

问题是当我尝试点击 tableView 行单元格打开另一个视图控制器时,它失败并显示表格视图单元格的选定状态.

这是快照.

//HomeCollectionViewCell.swift类 HomeCollectionViewCell: UICollectionViewCell {覆盖 func layoutSubviews() {super.layoutSubviews()设置单元格视图()}func setUpCellView() {让 frame = CGRect(x:20, y:20, width: bounds.width - 40, height: 600)让单元格 = CellView(框架:框架)contentView.addSubview(单元格)}}//CellView.swift类 CellView:UITableView {让 quoteCell = "QuoteCell"让 newsCell = "NewsCell"让 articleCell = "ArticleCell"覆盖初始化(框架:CGRect,样式:UITableViewStyle){super.init(frame: frame, style: .grouped)self.layer.cornerRadius = 15self.backgroundColor = .whiteself.dataSource = selfself.delegate = 自己self.register(QuoteTableViewCell.self, forCellReuseIdentifier: quoteCell)self.register(NewsTableViewCell.self, forCellReuseIdentifier: newsCell)self.register(ArticleTableViewCell.self, forCellReuseIdentifier: articleCell)}需要初始化?(编码器aDecoder:NSCoder){fatalError("init(coder:) 尚未实现")}}扩展单元格视图:UITableViewDelegate {func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) ->CGFloat {切换 indexPath.section {情况 0:返回 35案例1:返回140情况 2:返回 100情况 3:返回 140默认值:返回 0}}}扩展单元格视图:UITableViewDataSource {func numberOfSections(in tableView: UITableView) ->整数{返回类别.count}func tableView(_ tableView: UITableView, titleForHeaderInSection 部分: Int) ->细绳?{退货类别[部分]}func tableView(_ tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{返回 1}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {切换 indexPath.section {case 0: let cell = tableView.dequeueReusableCell(withIdentifier: dateCell)cell?.textLabel?.text = "今天"cell?.textLabel?.font = UIFont.systemFont(ofSize: 30, weight: UIFont.Weight.heavy)返回单元格!情况 1:让 cell = tableView.dequeueReusableCell(withIdentifier: quoteCell) as!报价表视图单元格返回单元格情况 2:让 cell = tableView.dequeueReusableCell(withIdentifier: newsCell) as!新闻表视图单元格返回单元格情况 3:让 cell = tableView.dequeueReusableCell(withIdentifier: articleCell) as!文章TableViewCell返回单元格默认值:让单元格 = tableView.dequeueReusableCell(withIdentifier: commonCell)cell?.textLabel?.text = "LOL"返回单元格!}}func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {切换 indexPath.section {case 0: print("选择日期")案例 1:打印(报价选择")案例2:打印(新闻选择")情况 3:让 homeViewController = HomeViewController()让 articleDetailViewController = ArticleDetailViewController()//homeViewController.show(articleDetailViewController, sender: homeViewController)//homeViewController.navigationController?.pushViewController(articleDetailViewController, animation: true)homeViewController.present(articleDetailViewController,动画:true,完成:nil)print("文章被选中")默认值:打印(大声笑")}}}

//HomeViewController.swift

class HomeViewController: UIViewController {覆盖 func viewDidLoad() {super.viewDidLoad()设置导航栏()view.addSubview(collectionView)设置约束()配置(集合视图:集合视图)}func setUpConstraints() {_ = collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 10, leftConstant: 10, bottomConstant: 10, rightConstant: 10, widthConstant: 0, heightConstant:0)collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true}懒惰 var collectionView : UICollectionView = {让布局 = UICollectionViewFlowLayout()layout.scrollDirection = .vertical让 cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)cv.translatesAutoresizingMaskIntoConstraints = falsecv.alwaysBounceVertical = 真cv.clipsToBounds = 真cv.showsHorizo​​ntalScrollIndicator = falsecv.showsVerticalScrollIndicator = falsecv.backgroundColor = .clearcv.isHidden = 假返回简历}()}私人让重用标识符 = "单元格"扩展 HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {内部功能配置(集合视图:UICollectionView){collectionView.register(HomeCollectionViewCell.self,forCellWithReuseIdentifier:reuseIdentifier)collectionView.dataSource = selfcollectionView.delegate = selfcollectionView.contentInset = UIEdgeInsets(顶部:0,左侧:0,底部:20,右侧:0)}func numberOfSections(in collectionView: UICollectionView) ->整数{返回 1}func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 部分: Int) ->整数{返回 7}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for:indexPath) as!HomeCollectionViewCell返回单元格}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) ->CG尺寸{返回 CGSize(width: collectionView.bounds.width, height: 600)}}

请告诉我哪里做错了或者我应该使用什么方法?

注意 - 不使用故事板/IB.仅以编程方式完成任务.

解决方案

从你做了什么,我想指出从 UView<中呈现 UIViewController 并不是一个好主意/代码>.您必须编写一些自定义委托,一旦有人点击自定义 CellView 类中的这些单元格,这些委托就会被触发.这些委托必须在包含 tableview 的视图控制器中实现.您必须从 UIViewController 编写代码来呈现新的视图控制器.

I have the Main View Controller which has a collection view with its collection view cells each initialized as a tableView to serve multiple rows inside of that collection view cell. If you're getting confused, below is the snapshot of the current state.

The problem is when I try to tap a tableView row cell to open another view controller, It fails and a selected state of table view cell is shown.

Here is the snapshot.

//HomeCollectionViewCell.swift
class HomeCollectionViewCell: UICollectionViewCell {
override func layoutSubviews() {
    super.layoutSubviews()
    setUpCellView()
}
func setUpCellView() {
    let frame = CGRect(x:20, y:20, width: bounds.width - 40, height: 600)
    let cell = CellView(frame: frame)
    contentView.addSubview(cell)
  }
}

//CellView.swift
class CellView: UITableView {
    let quoteCell = "QuoteCell"
    let newsCell = "NewsCell"
    let articleCell = "ArticleCell"
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: .grouped)
        self.layer.cornerRadius = 15
        self.backgroundColor = .white
        self.dataSource = self
        self.delegate = self
        self.register(QuoteTableViewCell.self, forCellReuseIdentifier: quoteCell)
        self.register(NewsTableViewCell.self, forCellReuseIdentifier: newsCell)
        self.register(ArticleTableViewCell.self, forCellReuseIdentifier: articleCell)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension CellView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    switch indexPath.section {
        case 0: return 35
        case 1: return 140
        case 2: return 100
        case 3: return 140
        default: return 0
    }
  }
}
extension CellView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
    return categories.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return categories[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.section {
        case 0: let cell = tableView.dequeueReusableCell(withIdentifier: dateCell)
                cell?.textLabel?.text = "Today"
                cell?.textLabel?.font = UIFont.systemFont(ofSize: 30, weight: UIFont.Weight.heavy)

        return cell!
        case 1: let cell = tableView.dequeueReusableCell(withIdentifier: quoteCell) as! QuoteTableViewCell
        return cell
        case 2: let cell = tableView.dequeueReusableCell(withIdentifier: newsCell) as! NewsTableViewCell
        return cell
        case 3: let cell = tableView.dequeueReusableCell(withIdentifier: articleCell) as! ArticleTableViewCell
        return cell
        default: let cell = tableView.dequeueReusableCell(withIdentifier: commonCell)
        cell?.textLabel?.text = "LOL"
        return cell!
    }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.section {
    case 0: print("Date Selected")
    case 1: print("Quote Selected")
    case 2: print("News Selected")
    case 3: let homeViewController = HomeViewController()
            let articleDetailViewController = ArticleDetailViewController()
//homeViewController.show(articleDetailViewController, sender: homeViewController)//homeViewController.navigationController?.pushViewController(articleDetailViewController, animated: true)
    homeViewController.present(articleDetailViewController, animated: true, completion: nil)
            print("Article selected")
    default: print("LOL")
    }
  }   
}

//HomeViewController.swift

class HomeViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    setupNavBar()
    view.addSubview(collectionView)
    setUpConstraints()
    configure(collectionView: collectionView)
}
func setUpConstraints() {
    _ = collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 10, leftConstant: 10, bottomConstant: 10, rightConstant: 10, widthConstant: 0, heightConstant: 0)
    collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}

lazy var collectionView : UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.alwaysBounceVertical = true
    cv.clipsToBounds = true
    cv.showsHorizontalScrollIndicator = false
    cv.showsVerticalScrollIndicator = false
    cv.backgroundColor = .clear
    cv.isHidden = false
    return cv
}()
}
private let reuseIdentifier = "Cell"
extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
internal func configure(collectionView: UICollectionView) {
    collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 7
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HomeCollectionViewCell
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: 600)
}
}

Please tell where I'm doing wrong or What approach should I use?

Note- No use of storyboards/IB. Done things programmatically only.

解决方案

From what have you done, I want to point out that its not a good idea to present UIViewController from UView. You must write some custom delegates which will get fired once someone taps on those cells in the custom CellView class. Those delegates must be implemented in the view controller that contains the tableview. From the UIViewController you must write the code to present the new viewcontrollers.

这篇关于如何在选择 tableView 的行单元格时显示视图控制器(作为集合视图单元格)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆