2017-03-16 94 views
0

我有一个应用程序,检查用户是否有一个特定的文件下载与否,如果他们没有提醒他们有机会下载它。这段代码是从UITableViewCell中调用的,但我不知道如何调用带有tableView的视图控制器来模拟按下第一行(必需的文件总是在第一行)。模拟tableview行从TableViewcell选择Swift

下面是一个代码片段

if (fileLbl.text == baseMapDisplayname) { 
      let alertController = UIAlertController(title: "Basemap Not Downloaded", message: "Please first download the Offline Basemap", preferredStyle: .alert) 

      var rootViewController = UIApplication.shared.keyWindow?.rootViewController 
      if let navigationController = rootViewController as? UINavigationController { 
       rootViewController = navigationController.viewControllers.first 
      } 
      if let tabBarController = rootViewController as? UITabBarController { 
       rootViewController = tabBarController.selectedViewController 
      } 

      alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel ,handler: nil)) 
      alertController.addAction(UIAlertAction(title: "Download", style: UIAlertActionStyle.default,handler: { (action: UIAlertAction!) in 
       //TODO - Simulate action of selecting first row of tableview 

       //this does not work 
       let indexPath = IndexPath(row: 0, section: 0) 
       MainVC().tableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom) 
       MainVC().tableView.delegate?.tableView!(tableView, didSelectRowAt: indexPath) 

      })) 
      rootViewController?.present(alertController, animated: true, completion: nil) 

     } 
+0

在我看来,你正在创建MainVC的新实例,你不能使用自我? 如果你有正确的控制器实例selectRow应该工作,并且你也不需要委托,当自己已经是tableview委托。 – silentBob

回答

0

试试这个:

let indexPath = IndexPath(row: 0, section: 0); 
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none) 
self.tableView(self.tableView, didSelectRowAt: indexPath) 
+0

这不起作用,因为tableView不存在于UITableViewCell的上下文中 – Nate23VT

+0

这与表格单元格无关,它是关于通知控制器拥有行选择的tableView。 如果你没有对MainVC实例的引用,你可以使用delegate(协议,上面建议),回调块(扩展UIAlertController),通知(NotificationCenter),alertController的presentsController等 – silentBob

1

你需要编写一个简单的协议,您MainVC符合,它会需要包括的功能通知MainVC已按下“下载”按钮。事情是这样的:

protocol DownloadDelegate { 
    func shouldDownloadFile() 
} 

所以你需要设置MainVC如在有警报通过创建像var downloadDelegate: DownloadDelegate?变量弹出的类DownloadDelegate,并在“下载”的行动,你可以说:

​​

这将通知MainVC,你可以做你已经计划在self.tableView.selectRow...事情作出反应。