ios - 如何在选择 tableView 的行单元格(作为 Collection View 单元格)时显示 View Controller ?

标签 ios swift uitableview uiviewcontroller uicollectionview

我有一个主视图 Controller ,它有一个 Collection View ,其 Collection View 单元格每个都初始化为 tableView,以服务该 Collection View 单元格内的多行。 如果您感到困惑,下面是当前状态的快照。

问题是当我尝试点击 tableView 行单元格来打开另一个 View Controller 时,它失败并显示 TableView 单元格的选定状态。

这是快照。

//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)
}
}

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

注意 - 不使用 Storyboard/IB。仅以编程方式完成任务。

最佳答案

提供标识符(“HomeViewController”和“ArticleDetailViewController”)来查看 Controller ,并在 didSelectRow() 中尝试以下代码。

case 3:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sourceViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "ArticleDetailViewController") as? ArticleDetailViewController
let navigator: UINavigationController = sourceViewController as! UINavigationController                                                                                                                                                       
navigator.pushViewController(destinationViewController!, animated: true)

关于ios - 如何在选择 tableView 的行单元格(作为 Collection View 单元格)时显示 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52274801/

相关文章:

objective-c - 在 iOS 中通过 UIImagePickerController 加载 UIActivityIndi​​cator

ios - 减小 iOS 应用程序文件大小

javascript - 网络语音 API : Consistently get the supported speech synthesis voices on iOS safari

ios - 可以使用 childByAutoId 进行 Firebase 多路径更新吗?

ios - 键盘出现时向上移动 UITextField 和 UITableView

ios - 如何从 UITableViewCell 内的 URL 设置 UIImageView 的图像?

swift - 选择当前表格 View 的一行时如何返回到上一个 View

Swift prepareForSegue 到许多自定义 ViewController 之一

ios - 尝试呈现其 View 不在窗口层次结构中的 <UIAlertController : 0x79151e00> on <Prisoners_Dillema. ControllerGame: 0x788b1a00>

xcode - NSClasses 与 Swift 新类