Subclassed UIView shows black background if drawRe

2019-07-29 22:43发布

问题:

I have a custom class which I derived from the UIView class. What I want to accomplish is just drawing vertical black lines with a predefined distance between. When I override the drawRect method and write my code to draw vertical lines, the view just shows a complete black background. Then I noticed that even an empty overridden drawRect which only calls the superclass' drawRect results in a black background. When I comment out the drawRect, then the view shows through and becomes transparent as I expected.

This is the only code I am using in the drawRect which just calls the superclass method:

- (void)drawRect:(CGRect)rect
{
   [super drawRect:rect];

}

What can be reason of this behavior?

回答1:

It's quite likely that there is some under-the-hood shenanigans going on with UIView, and that the base class doesn't actually implement drawRect, or some sneaky optimisation is happening.

The documentation does say not to call super if you are directly overriding UIView, and it also says you don't need to implement drawRect if all you do is set a background colour or you populate the content in other ways:

The default implementation of this method does nothing. Subclasses that use native drawing technologies (such as Core Graphics and UIKit) to draw their view’s content should override this method and implement their drawing code there. You do not need to override this method if your view sets its content in other ways. For example, you do not need to override this method if your view just displays a background color or if your view sets its content directly using the underlying layer object. Similarly, you should not override this method if your view uses OpenGL ES to do its drawing.

And:

If you subclass UIView directly, your implementation of this method does not need to call super. However, if you are subclassing a different view class, you should call super at some point in your implementation.

It's therefore quite likely that by calling super you are losing something. You don't show any of your actual drawing code so its difficult to see where you might be going wrong with that, but as a starting point, don't call super if you've directly overridden UIView.