我确定我在这里缺少一些愚蠢的东西,但是我有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)
答案 0 :(得分:0)
您不能将同一视图添加到两个单独的父视图。将其添加到其他视图后,它将从上一个视图中删除。如果要在两个视图上使用标签视图,只需创建它的两个实例。
forEach
答案 1 :(得分:0)
我尝试了使用不同背景颜色的相同代码,但发现没有问题,也许是因为背景颜色相同,所以它不可见。
请在下面找到代码
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