2017-02-18 7 views
2

私はイメージUIButtonを作成し、その位置をプログラムによってInterface Builderを使用して設定しようとしています。なぜなら、ViewControllerのロジックに基づいてボタンを表示/非表示にするからです。しかし、私は過去〜4時間無駄に検索して過ごしました。swift 3:UIViewでUIButtonを中央揃え(縦と横)する方法は?

class ViewController: UIViewController{ 
    //this is here so i can access playButton across different functions that i'll define in this ViewController 
    let playButton:UIButton = { 
     let play_btn = UIButton() 
     play_btn.setImage(UIImage(named:"my_button_image.png"), for: UIControlState.normal) 
     play_btn.translatesAutoresizingMaskIntoConstraints = false 
     return play_btn 
    }() 

    override func viewDidLoad() { 

     super.viewDidLoad() 


     playButton.addTarget(self, action:#selector(self.toggle), for: .touchDown) 
     let centerX = NSLayoutConstraint(item: self.playButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) 
     let centerY = NSLayoutConstraint(item: self.playButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) 

     self.view.addConstraints([centerX, centerY]) 

     view.addSubview(playButton) 

    } 
} 

私もしました:ここでは完全なコードですCGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)

に一見推奨方法

  • UIButton.centerプロパティを設定:

    1. 制約:私は、以下のアプローチを試してみました試してみました:playButton.center = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)

      など:上記の作品の

      playButton.center.x = self.view.center.x playButton.center.y = self.view.center.y

      なし:(

      すべてのヘルプ/アドバイス/提案は大歓迎です!

  • +0

    制約を設定する前に、スーパービューにボタンを追加することになっています。それがうまくいかない理由です。 – KrishnaCA

    答えて

    6

    あなたのコードを試したところ、クラッシュしました。ビュー

    を中心にボタンを作るために、私はボタンに簡単に作成することをお勧めしますが、いずれにせよ に)(

    を、ビューが初期化される前に、制約を追加しようとしている制約がviewWillLayoutSubviews内にある必要があります追加していた問題、すなわち

    let btn = UIButton(frame: CGRect(x:0 , y:0, width:100, heigth: 60)) 
    btn.center = self.view.center 
    self.view.addSubview(btn) 
    

    上記なり、自動的に制約

    はそれが役に立てば幸いビューの中央にあるボタン!

    +0

    上記のスニペットがviewDidLoad()内に追加されました –

    +0

    ありがとう@AndreeWijaya! 'viewWillLayoutSubviews()'関数の中に私の制約を追加することがトリックでした! –

    関連する問題