如何通过点击表视图单元格来过渡到视图控制器?我目前的结构是:
我使用navigation controller
作为浏览应用程序 atm 的唯一方式。
我使用struct
类型的view models
来表示单个单元格。这些视图模型符合自定义协议,该协议由我调用的方法组成cellSelected
。
那么我的问题是:
如何使用cellSelected
功能点击单元格来过渡到view controller
?这可能吗?
自定义协议:
protocol CellRepresentable
{
var reuseIdentier: String { get }
func registerCell(tableView: UITableView)
func cellInstance(of tableView: UITableView, for indexPath: IndexPath) -> UITableViewCell
func cellSelected()
}
视图模型示例:
struct ProfileNameViewModel
{
}
extension ProfileNameViewModel: TextPresentable
{
var text: String
{
return "Name"
}
}
extension ProfileNameViewModel: CellRepresentable
{
var reuseIdentier: String
{
get
{
return ProfileTableViewCell<ProfileNameViewModel>.reuseIdentifier
}
}
func registerCell(tableView: UITableView)
{
tableView.register(ProfileTableViewCell<ProfileNameViewModel>.self, forCellReuseIdentifier: ProfileTableViewCell<ProfileNameViewModel>.reuseIdentifier)
}
func cellInstance(of tableView: UITableView, for indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentier, for: indexPath) as! ProfileTableViewCell<ProfileNameViewModel>
cell.configure(withDelegate: self)
return cell
}
func cellSelected()
{
// ??
}
}
我想你有几个选择,你可以将导航控制器的引用传递给视图模型,或者你可以定义一个在cellSelected
上执行的闭包。
选项 1:
struct ProfileNameViewModel {
private let navigationController: UINavigationController
init(withNavigationController navigationController: UINavigationController) {
self.navigationController = navigationController
}
func cellSelected() {
navigationController.pushViewController(...)
}
}
选项 2:
struct ProfileNameViewModel {
private let selectedAction: () -> Void
init(withSelectedAction selectedAction: @escaping () -> Void) {
self.selectedAction = selectedAction
}
func cellSelected() {
selectedAction()
}
}
在视图控制器上:
let vm = ProfileNameViewModel(withSelectedAction: { [weak self] in
self?.navigationContoller?.pushViewController(...)
})
1-转到故事板,单击您的视图控制器,然后在xcode左侧的实用程序区域中,并为其提供故事板标识符。
2-回到你的代码并在cellSelected((中执行它
假设您的视图控制器称为MusicListVC
func cellSelected() {
if let viewController = storyboard?.instantiateViewController(withIdentifier: "your Identifier") as? MusicListVC
{
navigationController?.pushViewController(viewController , animated: true)
}
}