简体   繁体   中英

Is it possible to call another view controller's tableview didSelect index path and execute it?

First of all

I have a ViewController, it has Button

That button will be back to specific ViewController through Navigation

var viewControllers = self.navigationController!.viewControllers

while !(viewControllers.last is MainViewController) {  
             viewControllers.removeLast()
          }

let destinationViewController = self.storyboard?.instantiateViewController(withIdentifier: "destinationViewController") as! destinationViewController

viewControllers.append(destinationViewController)

self.navigationController?.setViewControllers(viewControllers, animated: false)

In my destinationViewController has TableView

I need to automatically conduct First row

So I write down these code before setViewControllers above

But get nil

let indexPath = IndexPath(row: 0, section: 0)
destinationViewController.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)  

Here's destinationViewController

class DestinationViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
      }
}
    extension DestinationViewController:UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
        //Here is user select can be triggered, but I want to call from another viewController
       }
    }

My question is how should I call tableView's row that I want from another viewController ?

Rather than destinationViewController.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) , why not call:

destinationViewController.
    tableView(destinationViewController.tableView, 
    didSelectRowAt: IndexPath(row: 0, section: 0))

simply do one thing, in your destination viewController update your tableView after viewDidAppear.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .top)
}

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