A good solution would be to add auto-layout constraints to your subviewContainer , since the constraints are automatically updated every time self.frame changes.
Your code will look like this:
required init(coder: NSCoder) { super.init(coder: coder) initSubComponents() } func initSubComponents() { // Original code, I removed debugging code for easier reading. subviewContainer = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) //Where the magic happens: subviewContainer.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: subviewContainer, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: subviewContainer, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: subviewContainer, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: subviewContainer, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0).isActive = true }
There are several ways to add auto-placement restrictions, click to find out here .
This is a bit more code, but overall a much better way to deal with this problem, as there are situations where drawRect will not be saved.