我的约束有什么问题?

时间:2017-04-03 02:02:26

标签: autolayout uikit constraints

我只是想创建一个视图,其中包含的视图高达50%。在下面的代码中,我设置约束来实现当我将视图添加到超级视图时。我将translatesAutoResizingMaskToConstraints设置为false,通过锚点添加约束。我还尝试调用setNeedsUpdateConstraints,并在updateConstraints中添加相同的约束。

但是在以下的Playground代码中,我没有看到受约束的子视图testView。我希望看到蓝色视图的大小是橙色视图的一半,但我看到的只是橙色。

我不确定我在这里缺少什么。

   //: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport


    class LView: UIView {

        var testView = UILabel()

        override init(frame: CGRect) {
            super.init(frame: frame)

            self.backgroundColor = .orange

            setup()
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        private func setup() {

            addSubview(testView)
            testView.backgroundColor = .blue

            testView.text = "....."
            //testView.setNeedsUpdateConstraints()

            testView.translatesAutoresizingMaskIntoConstraints = false

            testView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.5).isActive = true
            testView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5).isActive = true
            testView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
            testView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true


        }


    }

    let testView = LView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    PlaygroundPage.current.liveView = testView

0 个答案:

没有答案
相关问题