私はイメージ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)
に一見推奨方法
- 制約:私は、以下のアプローチを試してみました試してみました:
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
なし:(
すべてのヘルプ/アドバイス/提案は大歓迎です!
制約を設定する前に、スーパービューにボタンを追加することになっています。それがうまくいかない理由です。 – KrishnaCA