2017-03-18 4 views
0

自分のカスタムビューにAppearableプロトコルのメソッドを使用したいと思います。カスタムビュークラス内でUIImageViewを使用する適切な方法

protocol Appearable { } 

extension Appearable where Self: UIView { 

    func appear(duration: Double, delay: Double) { 
     self.alpha = 0 

     UIView.animate(withDuration: duration, delay: delay, options: .curveEaseIn, animations: { 
      self.alpha = 1 
      self.transform = CGAffineTransform(scaleX: 2.0, y: 1.5) 
     }, completion: nil) 

     self.transform = CGAffineTransform.identity 
    } 
} 

私のCustomView:私のMAINVIEWで

class CustomView: UIView, Appearable {} 

私は私が画面上に表示したい画像を使用して変数を作成しました。

class MainView: UIView { 
    let randomView: CustomUIView = { 
    var image = CustomUIView() 
    image = UIImageView(image: myImage) 

    return image 
} 

タイプ 'UIImageView'の値を 'CustomView'に割り当てることができないため、このコードは機能しません。私の質問は、この種の操作を行う適切な方法は何か。

答えて

1

CustomImageViewクラスを作成し、Appearableプロトコルに準拠させるのはなぜですか?

let imageView = CustomImageView() 
imageView.image = myImage 

を、デフォルトのプロトコルメソッドを使用します:

class CustomImageView: UIImageView, Appearable {} 

今あなたが必要なものを行うことができます答えを

imageView.appear(duration: 2.0, delay: 0.0) 
+0

感謝を。それは動作します。しかし、私はUIViewから継承し、同じことをするでしょうか?イメージをカスタムクラスにキャストするよりも良い選択肢がありますか? – Billy

+0

@Billy UIImageViewにあなたのプロトコルで拡張されたUIViewをキャストしようとしました。 UIImageViewはUIViewを拡張し、APIを調整したので、このようなキャストを行うのは不適切です。 UIImageViewクラスでプロトコルメソッドを呼び出す場合は、カスタムUIImageClassを作成し、プロトコルに準拠させます。 –

+0

ありがとうございました。 – Billy

関連する問題