2017-07-09 5 views
1

画像をアップロードする2つのTableViewCellがあり、コードは本質的に同じです。私がしたいことは、そのコードを取得して1つの関数にすることで、重複を減らすことができます。しかし、私は問題を適切にキャストしています。 2つのテーブルビューセルは、HomeTVCProfileTVCと呼ばれ、どちらも、profile_Imageという名前のUiImageViewを持っています。ここでiOS swift 3 switch文でどのようにタイプを変更できますか

は、私は上記のコードは、今ここで私はswitchステートメント内のエラーを取得しています機能

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 
      } 

      } 
    } 

あるHomeTVCのtableViewに属し明らか

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) 

} 

その関数を呼び出す方法ですon 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 
      } 
     } 
    } 

} 

はまた、あなたが同じプロパティを持つ2つのクラスを持っているとき、これはを使用するための素晴らしい機会です。プロファイル・イメージのオブジェクトにUIImageViewがあることを指定するプロトコルを作成できます。

protocol ProfileImageDisplaying { 
    var profileImageView: UIImageView 
} 

あなたは両方のセルは、このプロトコルを採用作ることができ、その後、あなただけの代わりに、2の(セルがProfileImageDisplayingであるかどうかを確認するために)1つのチェックを行う必要があります。

関連する問題