简体   繁体   中英

Adding subview to another subview using Auto Layout

I'm sure I am missing something stupid here, but I have mainView, subviewA, and subviewB. I am trying to add subviewB to subviewA and anchor it inside of subviewA, however it is not anchoring (just remains in top left corner. However, if I add subviewB to mainView and then anchor it, it works fine.

Example (using a custom anchoring function that I believe is self-explanatory):

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)

You cannot add the same view to two separate parent views. Once you add it to a different view, it will be removed from the previous view. If you want the label view on both views, simply create two instances of it.

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

I tried the same code with different background color and found nothing wrong with it, maybe because of same background color, it wont be visible.

Please find the code below

        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

请找到所附的屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM