2017-07-09 31 views
1

我有2個上傳圖像的TableViewCells,代碼基本相同。我想要做的就是獲得該代碼並將其加入1個函數,以便減少重複。然而,我無法正確地投射東西。這兩個tableview單元格稱爲HomeTVCProfileTVC它們都有一個名爲profile_Image的UiImageView。iOS swift 3如何更改switch語句中的類型

這是我如何調用該函數

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

homeProfile.sharedGetImage(cellType: cell,streamsModel: streamsModel, row: indexPath.row) 

} 

顯然上面的代碼屬於HomeTVC的tableView,現在這裏是功能

func sharedGetImage (cellType: UITableViewCell?,streamsModel: streamModel, row: Int) { 

     var cell = HomeTVC() 

     switch cellType { 

     case is HomeTVC : 
     cell = HomeTVC() 
     break 

     case is ProfileTVC : 
     cell = cell as! ProfileTVC 

     default : break 

     } 


     if streamsModel.profile_image_string[row] != "" { 

      if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage { 
       cell.profile_image.image = image 
      } 

      } 
    } 

我越來越switch語句中的錯誤在cell = cell as! ProfileTVC錯誤是從HomeTVC投射到ProfileTVC失敗的無關類型。我明白,我該如何解決這個問題?我想要做的是檢測UITableViewCell的類型,然後獲取一個變量並將其更改爲該類型,以便我可以訪問profile_image屬性。

回答

2

在你的sharedGetImage函數中,你傳遞了對錶格視圖單元格的引用,所以用它來代替創建一個新的單元格。

func sharedGetImage(cellType: UITableViewCell?, streamsModel: streamModel, row: Int) { 

    if let cell = cellType as? HomeTVC { 
     if streamsModel.profile_image_string[row] != "" { 
      if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage { 
       cell.profile_image.image = image 
      } 
     } 
    } 

    if let cell = cellType as? ProfileTVC { 
     if streamsModel.profile_image_string[row] != "" { 
      if let image = streamsModel.imageCache.object(forKey: streamsModel.profile_image_string[row] as AnyObject) as? UIImage { 
       cell.profile_image.image = image 
      } 
     } 
    } 

} 

或者,當你有兩個具有相同屬性的兩個類,這是一個很好的機會來使用。您可以創建一個協議來指定對象具有UIImageView用於配置文件圖像。

protocol ProfileImageDisplaying { 
    var profileImageView: UIImageView 
} 

你可以把兩個單元採用該協議,然後你只需要做一個檢查(看是否細胞是ProfileImageDisplaying),而不是兩個。