使用自动布局将子视图添加到另一个子视图

Adding subview to another subview using Auto Layout

我确定我在这里遗漏了一些愚蠢的东西,但我有 mainView、subviewA 和 subviewB。我正在尝试将 subviewB 添加到 subviewA 并将其锚定在 subviewA 内,但是它没有锚定(只是保留在左上角。但是,如果我将 subviewB 添加到 mainView 然后锚定它,它工作正常。

示例(使用我认为不言自明的自定义锚定功能):

addSubview(questionContainerView)
questionContainerView.anchor(topAnchor, left: leftAnchor, bottom: centerYAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)


// does not work
questionContainerView.addSubview(questionTextLabel)
questionTextLabel.anchor(questionContainerView.topAnchor, left: questionContainerView.leftAnchor, bottom: questionContainerView.bottomAnchor, right: questionContainerView.rightAnchor, topConstant: 25, leftConstant: 10, bottomConstant: 25, rightConstant: 10, widthConstant: 0, heightConstant: 0)

// does work
addSubview(questionTextLabel)
questionTextLabel.anchor(questionContainerView.topAnchor, left: questionContainerView.leftAnchor, bottom: questionContainerView.bottomAnchor, right: questionContainerView.rightAnchor, topConstant: 25, leftConstant: 10, bottomConstant: 25, rightConstant: 10, widthConstant: 0, heightConstant: 0)

您不能将同一视图添加到两个单独的父视图。一旦将它添加到不同的视图,它将从以前的视图中删除。如果你想在两个视图上都使用标签视图,只需创建它的两个实例即可。

questionContainerView.addSubview(questionTextLabel) // first time
addSubview(questionTextLabel) // second time the questionTextLabel is removed from questionContainerView

我用不同的背景颜色尝试了相同的代码,但没有发现任何问题,可能是因为相同的背景颜色,它不会可见。

请在下面找到代码

        self.view.addSubview(questionContainerView)
    questionContainerView.anchor(top: self.view.topAnchor, left: self.view.leftAnchor, bottom: self.view.centerYAnchor, right: self.view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
    questionContainerView.backgroundColor = .blue

    questionContainerView.addSubview(questionTextLabel)
    questionTextLabel.anchor(top: questionContainerView.topAnchor, left: questionContainerView.leftAnchor, bottom: questionContainerView.bottomAnchor, right: questionContainerView.rightAnchor, topConstant: 25, leftConstant: 10, bottomConstant: 25, rightConstant: 10, widthConstant: 0, heightConstant: 0)
    questionTextLabel.backgroundColor = .black