UIStackView未按预期显示

时间:2018-10-13 07:45:49

标签: swift constraints uistackview

我想向我的应用添加UIStackView登录按钮,因此我添加了以下代码:

override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews()


        SignInButtonsStackView.center.x = self.view.center.x
        SignInButtonsStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10)
        SignInButtonsStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 10)
        SignInButtonsStackView.spacing = 5


        SignInButtonsStackView.addArrangedSubview(FacebookSignInButton)
        SignInButtonsStackView.addArrangedSubview(GoogleSignInButton)

    }

我先设置UIStackView的约束,然后添加按钮。

我的目标是将来能够添加更多登录按钮,同时添加最少的代码。

这就是我得到的:

enter image description here

不仅宽度不一样,而且高度也弄乱了。

如何确保UIStackView中的所有项目的宽度,高度和间距相同?如何修复该视图以使其正常显示?

编辑

我在调试窗口中有这个

"<NSLayoutConstraint:0x600000288700 UILayoutGuide:0x6000007b0760'UIViewSafeAreaLayoutGuide'.bottom == UIStackView:0x7f9b04d15420.bottom + 187   (active)>",
    "<NSLayoutConstraint:0x600000288ac0 V:|-(499)-[UIStackView:0x7f9b04d15420]   (active, names: '|':UIView:0x7f9b04d166e0 )>",
    "<NSLayoutConstraint:0x60c000290f40 GIDSignInButton.height == 10   (active, names: GIDSignInButton:0x7f9b04d076e0 )>",
    "<NSLayoutConstraint:0x60800028cd50 'UISV-canvas-connection' V:[GIDSignInButton]-(0)-|   (active, names: GIDSignInButton:0x7f9b04d076e0, '|':UIStackView:0x7f9b04d15420 )>",
    "<NSLayoutConstraint:0x60c00028bb80 'UISV-canvas-connection' UIStackView:0x7f9b04d15420.top == FBSDKLoginButton:0x7f9b04d0a4d0'Continue with Facebook'.top   (active)>",
    "<NSLayoutConstraint:0x60c00028ad20 'UISV-fill-equally' GIDSignInButton.height == FBSDKLoginButton:0x7f9b04d0a4d0'Continue with Facebook'.height   (active, names: GIDSignInButton:0x7f9b04d076e0 )>",
    "<NSLayoutConstraint:0x60c000288610 'UISV-spacing' V:[FBSDKLoginButton:0x7f9b04d0a4d0'Continue with Facebook']-(5)-[GIDSignInButton]   (active, names: GIDSignInButton:0x7f9b04d076e0 )>",
    "<NSLayoutConstraint:0x60800028d1b0 'UIView-Encapsulated-Layout-Height' UIView:0x7f9b04d166e0.height == 736   (active)>",
    "<NSLayoutConstraint:0x600000288840 'UIViewSafeAreaLayoutGuide-bottom' V:[UILayoutGuide:0x6000007b0760'UIViewSafeAreaLayoutGuide']-(0)-|   (active, names: '|':UIView:0x7f9b04d166e0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x60c000290f40 GIDSignInButton.height == 10   (active, names: GIDSignInButton:0x7f9b04d076e0 )>

2 个答案:

答案 0 :(得分:1)

您不需要将高度限制设置为UIStackView。只需在UIButton's中设置UIStackView的高度约束,并在UIStackView中将其分配为“等间距”。

答案 1 :(得分:0)

我建议您添加SignInButtonsStackView.distribution = .fillEqually以获得相等的按钮高度,并添加SignInButtonsStackView.alignment = .fill以获得相同的宽度。

不幸的是,按钮的行为方式取决于其视图可能具有的内部约束。我建议检查控制台是否有与“无法满足的约束”相关的日志(为UIViewAlertForUnsatisfiableConstraints设置符号断点可能很有用https://staxmanade.com/2015/06/debugging-ios-autolayout-issues/)。