ios - 将约束应用于 Facebook 登录按钮

标签 ios swift uiview autolayout nslayoutconstraint

我正在尝试向 facebook 按钮添加约束以使其位于按钮处,这是我的代码;

...
let loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "email"]
loginButton.center = self.view.center

let myConstraint =
NSLayoutConstraint(item: loginButton,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1.0,
        constant: -20)
    self.view.addConstraint(myConstraint)

loginButton.addConstraint(myConstraint)

loginButton.delegate = self
self.view.addSubview(loginButton)

失败并出现以下错误;

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x15fd258a0 FBSDKLoginButton:0x15fe562d0'Log in'.bottom == UIView:0x15fd2fa60.bottom - 20>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.

有什么想法吗?

最佳答案

错误告诉您添加约束太早。您应该首先添加 loginButton,然后才添加约束:

loginButton.delegate = self

self.view.addSubview(loginButton)
self.view.addConstraint(myConstraint)
loginButton.addConstraint(myConstraint)

错误消息提到添加到 View 时,约束的项目必须是该 View 的后代。但是您在将实际按钮添加到 View 之前添加了 loginButton 的约束。

关于ios - 将约束应用于 Facebook 登录按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699803/

相关文章:

ios - BEMCheckBox 可设计失败

ios - 如果我使用 clearColor 作为 backgroundColor,我需要将 UIVIew.opaque 显式设置为 NO 吗?

ios - UICollectionView 部分出现小间隙

swift - 为什么将结构转换为 AnyObject 不是 swift 中的编译错误?

ios - 动画 : continuous heartbeat monitor lines

ios - 在 UITableViewCell 中将按钮右对齐

iphone - 不进行dealloc操作

ios - 我的应用程序在 ios6 中使用 UIAppearance setTintColor 关闭

ios - 嵌套违规。类型最多嵌套 1 层深

ios - 深层链接 Facebook iOS - 应用程序打不开