【问题标题】:Add a subview with constraints do not work添加带有约束的子视图不起作用
【发布时间】:2017-02-11 09:01:33
【问题描述】:

我想添加一个带有一些约束的子视图。

但我的观点没有出现。 下面是一些代码,有人知道出了什么问题吗?

(如果我添加一个 UITextField,例如它工作正常...)

class TestViewController:UIViewController {
    override func viewDidLoad() {
        //Do not work...
        addAndLayout(v: UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))


        //Works fine
        //addAndLayout(v: UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))
    }

    func addAndLayout(v:UIView) {
        v.backgroundColor = UIColor.red
        view.addSubview(v)

        v.translatesAutoresizingMaskIntoConstraints = false
        let leading = NSLayoutConstraint(item: v, attribute: .leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: v, attribute: .trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
        let top = NSLayoutConstraint(item: v, attribute: .top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
        view.addConstraints([leading, trailing, top])
    }
}

【问题讨论】:

    标签: swift uiview constraints addsubview


    【解决方案1】:

    添加高度约束或底部约束,您应该会看到视图。它与 UITextField 一起使用的原因是 UITextField 具有固有的内容大小,而 UIView 没有。

    【讨论】:

    • 没问题,在您适应之前,自动布局并不是最简单的事情。
    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多