我正在尝试将两个视图控制器内容添加到单个视图中。这里我正在尝试如何做到这一点。首先创建一个视图控制器,然后将需要的视图添加到私有函数中,然后调用 viewDidLoad 函数。
这是代码..
import UIKit
class CommonViewController: UIViewController {
private let viewModel: MoviesDetailsViewModel
init(viewModel: MoviesDetailsViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
navigationItem.largeTitleDisplayMode = .never
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
combineView()
navigationItem.leftBarButtonItem = UIBarButtonItem.backButton(target: self, action: #selector(didTapBack(_:)))
}
private func combineView() {
let dvc = MovieDetailsViewController(viewModel: viewModel)
let svc = SmiliarMovieViewController(viewModel: viewModel)
view.addSubview(dvc.view)
view.addSubview(svc.view)
}
@objc private func didTapBack(_ sender: UIBarButtonItem) {
navigationController?.popViewController(animated: true)
}
}
我将此 CommonViewController 调用到 didSelectRowAt 函数中,这里是它的代码。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let movie = viewModel.state.movies[indexPath.row]
let viewModel = MoviesDetailsViewModel(movie: movie, apiManager: APIManager())
let com = CommonViewController(viewModel: viewModel)
self.navigationController?.pushViewController(com, animated: true)
}
问题是当我选择表视图单元格时,我期望显示所选单元格的详细信息,但它不会呈现视图内容。请注意,当我尝试调用DetailsViewController(特定视图控制器)时,它能够显示内容。
这是屏幕截图..
请尝试容器视图控制器方法:
https://www.hackingwithswift.com/example-code/uikit/how-to-use-view-controller-containment