简体   繁体   中英

tableView.selectRow(...) doesn't work when I use UIAdaptivePresentationControllerDelegate (Swift 5)

In my app I use .present(...) to show one View Controller on top of the other (these are the same VC). When I dismiss it (pull down from screen) I want to select some row in my first VC. For it I use UIAdaptivePresentationControllerDelegate in which I have print(...) and tableView.selectRow(...) function. Print works fine, but tableView.selectRow doesn't work. What could be the issue?

extension UIViewController {
class func loadFromStoryboard<T: UIViewController>() -> T {
    let name = String(describing: T.self)
    let storyboard = UIStoryboard(name: name, bundle: nil)
    
    if let viewController = storyboard.instantiateInitialViewController() as? T {
        return viewController
    } else {
        fatalError("Error: No initial view controller in \(name) stroryboard")
    }
  }
}

class MyTabBarController: UITabBarController {
   let firstVC: FirstVC = FirstVC.loadFromStoryboard()
   ...
   override func viewDidLoad() {
    super.viewDidLoad()
    loadViewControllers()
   }

   private func generateViewController(rootViewController: UIViewController, image: UIImage?, title: String) -> UIViewController {
      let navigationVC = UINavigationController(rootViewController: rootViewController)
      ...
      return navigationVC
   }

   private func loadViewControllers() {
    viewControllers = [
        generateViewController(rootViewController: firstVC, image: ..., title: "...")
    ]
   }
   ...
   private func openVC() {
      let storyboard = UIStoryboard(name: "FirstVC", bundle: nil)
      let vc = storyboard.instantiateViewController(identifier: "FirstVC") as! FirstVC
      vc.presentationController?.delegate = vc
      self.present(vc, animated: true, completion: nil)
   }
   ...
}


//FirstVC
extension FirstVC: UIAdaptivePresentationControllerDelegate {
    func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
        print("VC was dismissed")
        self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .none)
    }
} 

In the console I see "VC was dismissed", but row doesn't select.

PS I use Xcode 12.2 and iOS 14.2. The tableView is an IBOutlet, if it's important.

You should set:

vc.presentationController?.delegate = self

Instead of:

vc.presentationController?.delegate = vc

Because you lose delegate as soon as you dismiss vc. You should listen dismissal of FirstVC on self where you present FirstVC.

If you just miss that it's ok. But if you can't understand why I can share more details:)

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