2017-09-06 87 views
-3

我想從類SecTableCell中的類ViewController訪問IBOutlet。 但它顯示了一個錯誤:如何在swift中訪問IBOutlet從一個類到其他類

fatal error: unexpectedly found nil while unwrapping an Optional value

class A: UIViewController{ 
    @IBOutlet var datePicker: UIDatePicker! 
} 

所以,在這裏我想訪問日期選擇在其他B類

class B:UITableViewCell{ 

    var obj=A() 

    @IBAction func datePickerAction(_ sender: Any) { 
     obj.datePicker.isHidden=false 
    } 
} 

請告訴我在做什麼錯在這裏。

+0

如果您的單元格中的數據選擇器,那麼你應該設置插座到你的UITableViewCell類 –

+0

但它不是在單元格上,它是在頂部視圖,我必須通過viewcontroller和datepic連接當某個單元格上的按鈕被點擊時,ker會顯示出來。 – user8350417

+0

在didSelectRowAtindexPath委託方法中顯示數據選取器 –

回答

0

據我所知,你已經創建了一個AUIViewController)這個新行。

var obj=A() 

此初始值設定項不會從「接口」構建器加載實例。因此這裏的A的IBOutletsnil,即datePickernil

當有按鈕的動作,BdatePickerAction被稱爲地方A存在,但它並沒有datePricer加載(即。它在這裏爲零),因此崩潰。

解決你的問題,你需要注入或在您的A(即self這裏)在細胞說飼料作爲

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    //... 
    cell.obj = self //Injection 
    //... 
} 

和B將然後進行修改,以接受類型objAoptional

class B:UITableViewCell{ 

    var obj: A? 
    @IBAction func datePickerAction(_ sender: Any) { 
     obj?.datePicker.isHidden=false 

    } 
} 
+0

我無法訪問cellForRowAt中的obj。 – user8350417

+0

請顯示您的tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)的外觀 – BangOperator