无法获取从UIView()继承的对象以在其父视图中正确定位

时间:2019-02-02 08:29:21

标签: ios swift uiview constraints frame

我试图将 UISquare()对象square放在其父视图squareParentView中。当我尝试使用自动版式实现这一目标时,我不幸失败了。

这是我的 UISquare 类供参考:

class UISquare: UIView() {

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

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

    override func draw(_ rect: CGRect) {
        //.. setup the square. Implementation details are not relevant to this question .. 
    }
}

这是我的 ViewController 类:

class viewController: UIViewController {

    let square = UISquare(x: 100, y: 100, width: 100, height: 100)

    let squareParentView = UIView()


    override func viewDidLoad() {
        super.viewDidLoad()


        view.addSubview(squareParentView)
        squareParentView.translatesAutoresizingMaskIntoConstraints = false

        // Here I am simply making squareParentView the same size as self.view
        squareParentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        squareParentView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        squareParentView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        squareParentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

       // Here I am setting up the square and enabling auto layout
       squareParentView.addSubview(square)
       square.translatesAutoresizingMaskIntoConstraints = false

       // PROBLEM AREA RIGHT HERE
       square.centerXAnchor.constraint(equalTo: squareParentView.centerXAnchor).isActive = true
       square.centerYAnchor.constraint(equalTo: squareParentView.centerYAnchor).isActive = true

    }
}

执行代码时,正方形只是没有出现在屏幕上。就像它完全忽略了自动布局,我的指示是将其中心放在其父视图的中心。

如果我摆脱了设置正方形约束的行(即,如果我根本不使用自动布局),则正方形将按预期显示在squareParentView的左上角。

我怀疑这不起作用的原因是,当您处理UIViews(例如 UISquare )时,仅更改布局约束是不够的,而仅是更改UIView的框架应该设置为所需的位置(例如,在我的情况下,设置square.center = squareParentView.center)。但是,当我设置它时,没有明显的区别。无论如何,我都不想在代码库中混合使用自动布局和框架,因此我想知道是否有一种方法可以排他地使用自动布局在其父视图中将该正方形居中


我还有一个后续问题:

我的代码中的一条打印语句显示出一些相当奇怪的东西:

print(squareParentView.center)        // prints (0,0)

为什么我以编程方式设置其约束时将父视图的中心设置为(0,0),以使其充满self.view

squareParentView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
squareParentView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
squareParentView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
squareParentView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

有什么作用?

1 个答案:

答案 0 :(得分:0)

将这两行添加到代码中:

 square.widthAnchor.constraint(equalToConstant: 100).isActive = true
 square.heightAnchor.constraint(equalToConstant: 100).isActive = true