ios - Swift 以编程方式添加约束

标签 ios iphone swift

我在 Storyboard编辑器的 UIViewController 中添加了一个 UILabel (amountLabel)。然后在 swift 文件 viewDidLoad 中,我以编程方式创建一个 UITextField (paymentTextField) 并尝试在 amountLabelpaymentTextField 之间添加约束。这是我在 viewDidload 中的代码:

let paymentTextField = UITextField()
    paymentTextField.translatesAutoresizingMaskIntoConstraints = false
    paymentTextField.frame = CGRectMake(15, 100, CGRectGetWidth(self.view.frame) - 30, 44)
    self.view.addSubview(paymentTextField)

    let bottonConstraint = NSLayoutConstraint(item: paymentTextField, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.amountLabel , attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 30)
    bottonConstraint.identifier = "paymentTextFieldSpacing"
    NSLayoutConstraint.activateConstraints([bottonConstraint])

但是我得到一个错误:

"Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items > and > because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal."

有谁知道哪里出了问题吗? amountLabel 直接拖到 Storyboard 中的 View ,并以编程方式将“paymentTextField”添加到同一 View 。为什么他们没有共同的祖先?

最佳答案

我遇到了您之前描述的相同问题。为了制作编程 subview (在您的情况下为 paymentTextField),您必须先将其添加到 subview ,然后应用您的约束。

通过将 subview 添加到第一个 View ,这确保了两个 View 具有相同的父 View 。

关于ios - Swift 以编程方式添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452908/

相关文章:

ios - 无法使用并找到 setTexture :resize SpriteKit

ios - lldb 无法在导入的 dylib 中查找符号

iphone - 通知中的图标

iphone - Cocoa错误260,文件路径结构

ios - UIStackview `fillProportionally` 分发问题

iOS 胖二进制文件 : should every arch include bitcode?

ios - 如何访问 SwiftyDropbox 错误的关联值?

ios - Xcode NSManagedObject 子类在标记为非可选时包含选项

Swift:显示来自 URL 的图像

Swift MapKit 不显示固定方向