Subclassed UIView is not visible, however content is visible

I subclassed UIView: http://pastebin.com/MVk1XmPS and when I add it to another UIViewController view:

self.myView = MyView.newAutoLayoutView()
self.myView.backgroundColor = UIColor.redColor()
self.view.addSubview(self.myView)

      

no red background. Seems to myView

have no width or height. However, the content is visible:

foto 07 11 14 23 12 36

I need to hardcode the size:

self.myView.autoSetDimensionsToSize(CGSize(width: 100, height: 100))

      

but shouldn't it automatically grow to fit the content? I am using swift, xcode6.1 and iOS8.1

+3


source to share


1 answer


Views don't automatically grow to fit their content. If you turn it clipsToBounds

on in your view, you will see the content disappear. Also, if you place a button as part of your content, you will see it, but you will not be able to interact with it because it is outside its bounds superview

.

In your subclass, you can implement methods sizeToFit

or sizeThatFits:

, but they will not be automatically called by the system. You should consider assigning constraints to your view in your storyboard. If you are not using a storyboard, you need to assign a frame in the viewWillLayoutSubviews

or method layoutSubviews

.



Storyboards will also please your custom view better if you implement intrinsicContentSize

.

+2


source







All Articles