【问题标题】:Adding layout constraints to a button [duplicate]向按钮添加布局约束[重复]
【发布时间】:2025-11-29 22:25:01
【问题描述】:

用 Swift 刷新自我...我想将此按钮 loginButton.center = self.view.center 置于视图底部的中心。当前代码将按钮完美地水平和垂直居中..

我尝试过使用 CGPoints 和 subView,但没有成功。

【问题讨论】:

  • 能贴出所有相关代码吗?
  • @Honey 唯一缺少的代码就是这个和那个let loginButton:PPLoginButton = PPLoginButton.init()
  • @JoshuaPaulsen 很高兴地说问题标题需要约束而不是框架布局

标签: ios swift autolayout cgpoint


【解决方案1】:

您似乎没有使用自动布局。所以这就是你要找的:

button.center = CGPoint(x: view.bounds.width / 2,
                        y: view.bounds.height - button.bounds.height / 2)

如果您想要使用自动布局,请选择 Sh_Khan 的答案。

【讨论】:

    【解决方案2】:
     let pos = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.maxY - 80)
           loginButton.center = pos
    
           loginButton.translatesAutoresizingMaskIntoConstraints = false
    
           self.view.addSubview(loginButton)
    

    【讨论】:

    • 您在此答案中将自动布局 (loginButton.translatesAutoresizingMaskIntoConstraints = false) 与手动设置框架 (loginButton.center = pos) 混合使用。
    • @AndréSlotta 谢谢!