2014-10-31 48 views
1

我正在使用Swift,我在tableview的didSelectRowAtIndexPath方法中出現錯誤。 我想傳遞一個值給另一個視圖控制器,即'secondViewController'。這裏EmployeesId是一個數組。相關代碼如下:在Swift中將值從一個視圖控制器傳遞給另一個視圖

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard 

    self.navigationController?.pushViewController(view, animated: true) 
    secondViewController.UserId = employeesId[indexPath.item] //getting an error here. 
} 

但我收到此錯誤: 致命錯誤:意外發現零而展開的可選值。

任何幫助將不勝感激。

+0

是什麼類型用戶ID?如果它是UILabel,那麼在視圖呈現之前它將爲零。另外,secondViewController的設置在哪裏? – 2014-10-31 14:43:07

+0

它應該是indexPath.row,而不是indexPath.item,但我不知道這是否能解決您的問題。你確定employeesId [indexPath.item]不是零嗎? – rdelmar 2014-10-31 14:58:10

+0

是seconfViewController中的UserId(強,非原子)? – casillas 2014-10-31 15:41:17

回答

4

下面是一個有兩個假設的通用解決方案。首先,UserId不是UILabel。其次,你的意思是使用view這是在第二行實例化,而不是使用secondViewController

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard 

    self.navigationController?.pushViewController(view, animated: true) 
    view.UserId = employeesId[indexPath.row] 
} 

這裏的儀表板是什麼樣子:

class Dashboard: UIViewController { 
    var UserId: String! 
    @IBOutlet var userIDLabel: UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
     userIDLabel.text = UserId 
    } 

    ... 
} 
+0

如果我想在viewDidLoad()中使用「userid」調用Web服務,我將如何調用,因爲用戶ID返回零 – 2017-12-08 06:20:03

0

UserId(strong, nonatomic)在secondViewController?

如果它很弱,它發送垃圾。你必須讓它變得強大。

1

使用「結構」中迅速3我們可以通過價值

  1. 在你的項目中創建一個快捷文件
  2. 在創建一個類SWIFT文件中像波紋管

    class StructOperation { 
         struct glovalVariable { 
         static var userName = String(); 
        } 
    } 
    
  3. Assing值設置爲「靜態無功username」的從第一個視圖控制器「StructOperation」級的「結構glovalVariable」變量像

    @IBAction func btnSend(_ sender: Any) { 
        StructOperation.glovalVariable.userName = "Enamul Haque"; 
        //Code Move to Sencon View Controller 
    } 
    
  4. 在目標視圖控制器產生得值像波紋管

    var username = StructOperation.glovalVariable.userName; 
    
+0

這是更好的方式還是傳遞全局值作爲其他控制器?@Enamul Haque – 2018-01-21 08:05:22

+0

謝謝@Dhaval Bhadania – 2018-01-21 10:29:33

相關問題