2017-07-17 8 views
0

UIViewサブクラスを作成して、必要なinitメソッドをデフォルトのものよりも強制的に使用するようにします。ユーザーに初期化のカスタム初期化メソッドを使用させる

それで、私はこれのための便利な方法を作成しました。

@available(*, unavailable, message: "init is unavailable.") 
public override init(frame: CGRect) { 
    super.init(frame: frame) 
} 

required 
convenience public init(withSomeParameters myParam:Type) { 
    self.init(frame: CGRect.zero) 
    //Doing something nice! 
} 

これは機能します。しかし、initにしようとすると、それを初期化する2つの方法が表示されます。ユーザーがカスタムinitメソッドを使用するように強制する方法は?

答えて

3

あなたはそれをプライベートにすることができ、ユーザはwithSomeParameters

class Test:UIView { 
    private override init(frame: CGRect) { 
     super.init(frame: frame) 
    } 

    convenience public init(withSomeParameters myParam:Type) { 
     self.init(frame: CGRect.zero) 
     //Doing something nice! 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
} 
でテストクラスを初期化する必要がある必要があります
0

たぶん、あなたは同様に利用できない初期化剤コーダをマークする必要があります。

@available(*, unavailable) 
    required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
} 

プラス:あなたの初期化子からconvenienceを削除し、別の例としてinit(frame:)

public init(withSomeParameters myParam:Type) { 
    super.init(frame: .zero) 
    //Doing something nice! 
} 

スーパークラスを呼び出し、ここにありますいくつかの基盤UIViewサブクラス私はストーリーボードを利用しない私の多くのプロジェクトで使用します:

class MXView: UIView { 
    init() { 
    super.init(frame: .zero) 
    } 

    // Storyboards are incompatible with truth and beauty. 
    @available(*, unavailable) 
    required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    } 
} 

サブクラス:あなたはそのようにそれを行う場合

class CustomView: MXView { 
    init(someParameters params: Type) { 
    // Phase 1: store ivars. 

    super.init() 

    // Phase 2: Do something nice. 
} 

CustomViewのユーザーがinit(someParamters:)を使用するように強制されます。 は非便利なinitであるため、init(frame:)はシャドウされています。

関連する問題