ios - nslayoutconstraint 不使对象出现

标签 ios swift4 nslayoutconstraint subview

我下面的代码使用代码无 Storyboard 来显示对象。该项目已构建,但我看不到我试图以编程方式放置的文本字段。我不知道为什么代码没有出现。我试图不使用 Storyboard。

 var enterWeight = UITextField()




override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(enterWeight)

    enterWeight.backgroundColor = UIColor.blue


    NSLayoutConstraint.activate ([

        enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
        enterWeight.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant : 20),
        enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
        enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),


        enterWeight.widthAnchor.constraint(equalToConstant: 50),
        enterWeight.heightAnchor.constraint(equalToConstant: 30)

        ])

}

最佳答案

你有相互冲突的约束,它们永远不会以这种方式工作。

首先,正如 iFlames 提到的,您需要将 translatesAutoresizingMaskIntoConstraints 设置为 false:

enterWeight.translatesAutoresizingMaskIntoConstraints = false

然后:

NSLayoutConstraint.activate ([
        enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
        enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
        enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),
        enterWeight.heightAnchor.constraint(equalToConstant: 30)
])

通过给textField一个前导和尾随,你已经隐式地给了它一个宽度约束,它是view的宽度减去常量(20 * 2),所以你不应该给它一个宽度约束,就会产生冲突。

关于ios - nslayoutconstraint 不使对象出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699531/

相关文章:

ios - 如何重新加载 SlideNavigationController 的内容

ios - ( objective-c )方法和变量如果只在自己的类中使用,是否需要在头文件(.h)中声明?

ios - 仅在 iOS 6 上使用特定字体剪辑的标签和文本字段文本

ios - UITextVIew 在屏幕上不可见

ios - 无法进行应用内购买

ios - 如何处理与 Swift 4 Codable 不一致的 JSON 格式?

ios - 为什么当从 Alamofire 响应触发代码时 KYDrawerController 不显示?

ios - 不将 WKWebView 保留在安全区域内的约束

swift - 动态添加 subview 后,NSSplitView 不调整 subview 的大小

ios - xcode 9.2 Storyboard中的不一致错误