简体   繁体   中英

Swift 4: New Viewcontroller when tapped on a cell with separate class

I have a tableview which has its own class in order to be reusable. My problem is that now I want to add:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath:IndexPath) {

tableView.deselectRow(at: indexPath, animated: false)
let vc = UIStoryboard(name: "Main", bundle:nil).instantiateViewController(withIdentifier: "eventView") as! eventView 
vc.event = self.eventsToLoad[indexPath.row]
self.present(vc, animated: true, completion:nil)

}

But as the tableview has its own class I cannot self will not have present method. I also do not want to use segue or navigationcontroller or anything, in order to be able to use this tableview anywhere.

If you are making the tableView to be its own delegate, then you have to add your own custom delegate to inform the presenter (in your case the viewcontroller) about the didSelectRowAt event.

Like:

protocol CustomTableViewDelegate: class {
    func customTableView(_ tableView: CustomTableView, didSelectRowAt indexPath: IndexPath)
}

class CustomTableView: UITableView, UITableViewDelegate {
    weak var customDelegate: CustomTableViewDelegate?
    //... other properties and UITableViewDelegate implementation
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        customDelegate?.customTableView(self, didSelectRowAt: indexPath)
    }
}

class SomeViewController: CustomTableViewDelegate {
    func customTableView(_ tableView: CustomTableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        let vc = UIStoryboard(name: "Main", bundle:nil).instantiateViewController(withIdentifier: "eventView") as! eventView 
        vc.event = self.eventsToLoad[indexPath.row]
        self.present(vc, animated: true, completion:nil)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM