2016-08-28 8 views
0

swiftで書かれたiOSアプリケーションのボタンビューオブジェクトをシーンにプログラムで追加しようとしています。私はここに答えを追いかけようとしていますhttps://stackoverflow.com/a/36263784すぐに制約を適切にアクティブにする方法

しかし、私はシーンのボタンを見ることができません。私はviewDidLoadメソッドからこのメソッドを呼び出します。

func buildLoginButton() -> UIButton 
{ 
    let button = UIButton() 
    button.backgroundColor = .greenColor() 
    button.setTitle("Test Button", forState: .Normal) 
    self.view.addSubview(button) 

    let c1 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) 

    let c2 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) 

    button.widthAnchor.constraintEqualToAnchor(nil, constant: 200).active = true 
    button.heightAnchor.constraintEqualToAnchor(nil, constant: 100).active = true 

    NSLayoutConstraint.activateConstraints([c1, c2]) 
    view.bringSubviewToFront(button) 

    return button 
} 
+0

デバッグペインのあいまいなレイアウトの制約に関する警告はありますか? – ozgur

+0

'buildLoginButton()'が呼び出されることを保証しましたか?メインスレッドでは? – BaseZen

答えて

1
let button = UIButton() 
self.view.addSubview(button) 

ストップ!あなたはこれを言うのを忘れ:

button.translatesAutoresizingMaskIntoConstraints = false` 

あなたがインターフェイスに入れて、作成した任意のビューでこれを言う、とに制約を適用しようとする必要があります。

関連する問題