一旦将Swift子视图约束/大小添加到UIView中,就不会更新

时间:2019-07-27 14:11:44

标签: swift xib custom-view

长话短说,我想将FavoriteBottomUIView添加到由标签“ 1”标识的UIView上。 UIView位于屏幕底部,是垂直UIStackView的最后一个单元格(黄色)。

class MainViewController: ParentUIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupBottomViews()
    }

    private func setupBottomViews() {
        // The questionview is a custom UIView which is being made with a ".xib" in the parent VC.
        // The questionView elements are all good

        // get the last cell from the UIStackView
        let bottomView: UIView = questionView.viewWithTag(1)!

        // Inflate the new favorite bottom ui view with .xib
        let nib = UINib(nibName: "FavoriteBottomUIView", bundle: nil)
        guard let view = nib.instantiate(withOwner: self, options: nil).first as? FavoriteBottomUIView else { fatalError("Error loading \(self) from nib") }

        // For debug purpouse change the custom view's bg to blue
        view.backgroundColor = .blue
        view.frame = bottomView.bounds
        bottomView.addSubview(view)

        view.frame.origin.x = 0
        view.frame.origin.y = 0

        // Make the custom view constraints to be equal with the super views (in our case is the bottom cell) anchors
        view.bindFrameToSuperviewBounds()

        // THE PROBLEM IS HERE !!!

        // For debug purpouse, the custom view contains another UIView which size should be all fit (width and height)
        view.mainView.backgroundColor = .red
    }
}

extension UIView {
    func bindFrameToSuperviewBounds() {
        guard let superview = self.superview else {
            return
        }

        self.translatesAutoresizingMaskIntoConstraints = false
        self.topAnchor.constraint(equalTo: superview.topAnchor, constant: 0).isActive = true
        self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0).isActive = true
        self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0).isActive = true
        self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: 0).isActive = true

    }
}

使用上面的代码,我试图添加另一个自定义视图(膨胀形式的xib,名为:FavoriteBottomUIView)并将其添加到最后一个单元格(黄色)。

这是自定义questionView xib:

enter image description here

enter image description here

如果您已经注意到,由于我更改了自定义视图的背景颜色view.backgroundColor = .blue,因此黄色现在变成了蓝色,现在整个单元格都被蓝色的自定义视图的“ contentView”填充了。

问题来自于自定义视图的(FavoriteBottomUIView)子视图

自定义视图有1个子级,即UIView,它是红色的view.mainView.backgroundColor = .red。此视图应填满整个单元格(蓝色根本不可见)。

FavoriteBottomUIView.xib:

enter image description here

0 个答案:

没有答案