2017-05-27 89 views
-1

我幾乎是Swift編程中的新手。我正在使用Swift 3和最新版本的Xcode,我試圖做一些對你們來說可能很容易的事情,所以在這裏:無法生成動態UITableView

我想動態填充一個TableView從Firebase數據庫中檢索數據。爲此,我設計了一個Prototype單元,其中包含一個UIImageView,一些UILabels和一個步進器。我認爲Stepper和其中一個UILabel不需要在生成時進行編輯。但我需要放置圖片並編輯2個UILabels。以下是我正在嘗試這樣做:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    //Set cell contents 
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId) 

    let imageView = cell?.viewWithTag(0) as! UIImageView 
    var price:UILabel = cell?.viewWithTag(2) as! UILabel 
    var name:UILabel = cell?.viewWithTag(1) as! UILabel 
    let amount = cell?.viewWithTag(3) as! UILabel 
    name.text = productList[indexPath.row].name 
    price.text = "" + (productList[indexPath.row].price?.description)! 
    let imageDict:NSDictionary = productList[indexPath.row].imageName! 

    let image = downloadImageProductFromFirebase(append: imageDict["hash"] as! String) 
    imageView.image = image 


    return cell! 
} 

當我運行應用程序,這是我發現的錯誤:

無法投類型的值「UITableViewCellContentView」(0x10442bff8)到「的UIImageView '(0x10441c738)。

但是有些東西很好,我知道從Firebase中正確地檢索數據,導致它在生成TableView單元格之前通過控制檯進行打印。

在此先感謝,夥計們!

+0

'讓的ImageView =細胞.viewWithTag(0)作爲! UIImageView'找到單元格的contentView,因爲'0'是視圖的默認標籤值。爲你的'UIImageView'使用另一個標籤值。 – vacawama

回答

2

看來,tableview單元格的內容視圖已經有了標籤0。您可以爲圖像視圖指定另一個標記號,或者更好:創建一個自定義子類並將@IBOutlets連接到單元格。這使得它更安全,並且在訪問視圖時甚至可以自動完成。

+0

棒極了!作爲vacawama,你首先嚐試解決它!現在我又遇到了另一個問題(對不起,如果我太討厭):錯誤移動到第一個UILabel,我試圖修改:無法將類型'UITableViewCell'(0x109cb1778)的值轉換爲'UILabel'(0x109cad268)。任何額外的幫助? –

+1

請勿使用標籤。創建一個自定義的UITableViewCell子類,將其分配給您的tableview並創建一堆@IBOutlets並將您的標籤連接到它們。然後將cellForRowAt中的單元格轉換爲您的自定義單元類並直接訪問視圖。 – xxtesaxx

+0

好吧!看起來很容易!我可以遵循的任何教程來做到這一點? =)真的謝謝你,男人! –

1

我的朋友創造一個UITabelViewCell子類,並連接IBOutlets您UIImageViewUILabel那裏,叫他們在cellForRowAt。這是正確的做法。

方法如下:

  1. 創建一個UITableViewCell子類 點擊文件 - >新建 - >可可觸摸--->然後選擇UITableViewCell子類,並記下的名字類如:ProductsTableViewCell

  2. 點擊你的故事板的動態電池原型,然後點擊自定義類的身份檢查器中更改類名ProductsTableViewCell

  3. 在單元格中添加您的UIImageView和UILabels,然後在ProductsTableViewCell.swift文件中爲它們創建IBOutlets。我們在第一步創建的子類。

  4. 現在在您的cellForRowAt函數中調用此原型單元格的IBOutlets並更改其內容。 實施例的代碼:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! ProductsTableViewCell 
    
    cell.imageView.image = downloadImageProductFromFirebase(append: imageDict["hash"] as! String) 
    cell.nameLabel.text = productList[indexPath.row].name 
    cell.priceLabel.text = "" + (productList[indexPath.row].price?.description)! 
    
    return cell 
    } 
    
+0

非常感謝很多人!還要感謝你的朋友!它真的幫助了我! –