Swift 程序约束 view.bottomAnchor 导致问题

标签 swift

我正在努力克服所有程序限制。

我创建了一个我想要做的界面表示,以确保所有内容都变成蓝色并且在运行时不会出现错误。

在界面生成器中,我创建了一个 UIView,将比例设置为 1:1,顶部 anchor 100,底部 anchor 450,并水平约束它。

效果很好。

现在我删除了所有这些并通过代码完成

我认为这应该与 IB 版本相同......

let testView = UIView()

view.addSubview(testView)
        testView.backgroundColor = .red


        let testViewTopConstraint = testView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)
        let testViewBottomConstraint = testView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 450)
        let testViewCenterXConstraint = testView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let testViewAspectConstraint = NSLayoutConstraint(item: testView,
                                                          attribute: .height,
                                                          relatedBy: .equal,
                                                          toItem: testView,
                                                          attribute: .width,
                                                          multiplier: (1.0 / 1.0),
                                                          constant: 0)


        NSLayoutConstraint.activate([testViewTopConstraint, testViewBottomConstraint, testViewCenterXConstraint, testViewAspectConstraint])

        testView.translatesAutoresizingMaskIntoConstraints = false

当我运行它时,红色方 block 变成一个延伸到末端(可能超出)的矩形。

我已经尝试过程序限制。如果我要添加一个主导约束,我完全没问题,但这似乎是我的底部约束,总是让我陷入困境。

我的底部约束有什么问题? 还是我做错了什么?

最佳答案

有一些事情,但要在这里回答您的特定问题,您只需在 450 常量中添加一个 -

let testViewBottomConstraint = testView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -450)

您还可以通过添加更多 anchor 来省略 NSLayoutConstraint。

关于Swift 程序约束 view.bottomAnchor 导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537060/

相关文章:

ios - 在自定义 tableview 单元格中本地化按钮和标签 [swift]

swift - 使用 SwiftJSON 将 Alamofire 结果 JSON 加载到 TableView 中

ios - 导航 Controller 之间的segue

ios - 在 Swift 中将阿拉伯字符串转换为英文数字

swift - 没有候选人产生预期的结果

ios - Alamofire 图片 : Placeholder image is not set for af_setImageWithURL

ios - 在 UIView 中循环遍历 UIButtons

ios - 如何将值从一个函数传递到另一个函数?

swift - 沿椭圆形 UIBezierPath 为 CAShapeLayer 设置动画

swift - Ubuntu 14.04 (Windows) 上的 Vapor 设置错误