2017-03-16 93 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...事情作出反應。