iphone - 如果drawRect : is overridden,子类UIView显示黑色背景

标签 iphone ios uiview overriding drawrect

我有一个从 UIView 类派生的自定义类。我想要完成的只是绘制具有预定义距离的垂直黑线。当我重写 drawRect 方法并编写代码来绘制垂直线时, View 只显示一个完整的黑色背景。然后我注意到,即使是一个只调用父类(super class)的 drawRect 的空覆盖 drawRect 也会导致黑色背景。当我注释掉drawRect时, View 会显示出来并像我预期的那样变得透明。

这是我在 drawRect 中使用的唯一代码,它只调用父类(super class)方法:

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

}

这种行为的原因是什么?

最佳答案

UIView 很可能有一些幕后的恶作剧,并且基类实际上并没有实现 drawRect,或者正在发生一些偷偷摸摸的优化。

如果您直接覆盖 UIView,文档确实说不要调用 super,并且它还说如果您所做的只是设置背景颜色或以其他方式填充内容,则不需要实现 drawRect:

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.



和:

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.



因此,通过调用 super 你很可能会失去一些东西。您没有显示任何实际的绘图代码,因此很难看出您可能在哪里出错,但作为起点,如果您直接覆盖 UIView,请不要调用 super。

关于iphone - 如果drawRect : is overridden,子类UIView显示黑色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14074281/

相关文章:

ios - 带有 Jquery Mobile 的 Phone Gap 不会打开内部链接

ios - 尝试从下向上而不是自上而下为 UIView 高度设置动画

iphone - 如何使用cocos2d获取用户输入

ios - 从 UIWebView 中删除渐变背景?

ios - GADBannerView 滚动与 UITableView IOS

iphone - 在 objective-c 中存储静态数组的位置

ios - 旋转后 UIView 坐标被交换但 UIWindow 不是?

ios - 如何将按钮移动到随机位置?

ios - 如何使 UIScrollView/UIPageControl 无限?

jquery - 移动开发和屏幕尺寸