gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:14:44 26 4
gpt4 key购买 nike

我有一个从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com