2017-09-15 40 views
0

我有一個任務,我應該在視圖控制器中使用表格視圖和自定義單元格創建產品列表。我定製了單元格,編譯時出錯。如何將自定義單元連接到UIViewController?

class ElectronicsTableViewCell: UITableViewCell { 

    @IBOutlet weak var productNameLabel: UILabel! 
    @IBOutlet weak var buyLabel: UILabel! 
    @IBOutlet weak var primeLabel: UILabel! 
    @IBOutlet weak var priceLabel: UILabel! 
} 


class ProductListViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{ 

    @IBOutlet weak var tableView:UITableView! 

    var electronicProducts = ["Swift DVD","Swift Manual","Beats EarPhones","IPad","I Watch"] 
    var price = ["45","34","67","90","89"] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.delegate=self 
     tableView.dataSource=self 

     tableView.register(UITableViewCell.self, forCellReuseIdentifier: "LabelCell") 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return electronicProducts.count 
    } 


     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell",for: indexPath as IndexPath) as! ElectronicsTableViewCell 

     let productName = electronicProducts [indexPath.row] 
     cell.productNameLabel?.text = productName 


     cell.buyLabel?.text = "Buy" 

     cell.primeLabel?.text = "Prime Eligible" 

     let productPrice = price [indexPath.row] 
     cell.priceLabel?.text = productPrice 


    return cell 
    } 

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     print("you selected cell \(indexPath.row)") 
    } 

} 

錯誤是: 從私人有效的用戶設置讀取。 無法將類型'UITableViewCell'(0x10300f858)的值轉換爲'assignment2.ElectronicsTableViewCell'(0x1013b3178)。 (LLDB)

回答

3

我認爲主要的問題是與線:

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "LabelCell") 

您需要註冊您的自定義類,所以改變的UITableViewCell到ElectronicsTableViewCell。

希望有所幫助。

0

假設您已經在故事板中爲TableViewCell標記了類,這是否有可能出現this question 的重複也要避免使用強制轉換。嘗試

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell",for: indexPath as IndexPath) 
     if let labelCell = cell as? ElectronicsTableViewCell { 
     let productName = electronicProducts [indexPath.row] 
     labelCell.productNameLabel?.text = productName 


     labelCell.buyLabel?.text = "Buy" 

     labelCell.primeLabel?.text = "Prime Eligible" 

     let productPrice = price [indexPath.row] 
     labelCell.priceLabel?.text = productPrice 
     return labelCell 
     } 
    return cell 
    } 
相關問題