I subclassed UIView: http://pastebin.com/MVk1XmPS and when I add it to another view of a UIViewController:
self.myView = MyView.newAutoLayoutView()
self.myView.backgroundColor = UIColor.redColor()
self.view.addSubview(self.myView)
the red background is missing. It seems that myView
has no width and height. However the content is visible:
I have to hard code the dimension:
self.myView.autoSetDimensionsToSize(CGSize(width: 100, height: 100))
but shouldn't it grow automatically by the size of the content? I use swift, xcode6.1 and iOS8.1
Views do not automatically grow to fit their content. If you enable clipsToBounds
on your view, you will see the content disappear. Alternatively, if you put a button as part of your content, you will see it but be unable to interact with it because it is outside of its superview
's bounds.
In your subclass, you could implement the sizeToFit
or sizeThatFits:
methods, but these are not going to be automatically called by the system. You should consider assigning constraints for your view in your storyboard. If you're not using a storyboard, you will need to assign a frame in your viewWillLayoutSubviews
or layoutSubviews
method.
Storyboards will also like your custom view better if you implement intrinsicContentSize
.