混乱时未调用UIView的drawRect [英] UIView's drawRect not being called when swizzled

查看:65
本文介绍了混乱时未调用UIView的drawRect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试先进的Objective-C方法。我想要实现的是将特定的绘图代码附加到现有的 UIView

I am experimenting with advanced Objective-C methods. What I want to achieve is to append specific drawing code to an existing UIView.

我很容易上手,继续在类别中声明我自己的 drawRect 方法:

I started easily, I went on to declare my own drawRect method in a category:

@interface UIView (Swizzled)

- (void)my_drawRect:(CGRect)rect;

@end

然后我将 drawRect刷掉了 UIView 方法的实现类别:

Then I swizzled the drawRect method of UIView in the implementation of the category:

+ (void)load
{
    [self swizzleInstanceMethod:@selector(drawRect:) withMethod:@selector(my_drawRect:) inClass:[UIView class]];
}

- (void)my_drawRect:(CGRect)rect
{
    NSLog (@"Test.");
}

此方法的实现在 GitHub ,并且在其他所有情况下也可以使用。 >

Implementation of this method is available on GitHub and the swizzling works in all other cases.

因此,根据逻辑,每次调用 drawRect 时,它应该只打印出测试。但这是行不通的,我调用的方法永远不会被调用。我继续发现我在这里做错了什么,但是我越看越多,我相信问题就出在其他地方。

So according to the logic, every time drawRect is called, it should just print out "Test". But it does not work, the method I swizzled is never called. I went on to discover what I did wrong here, but the more I look at it, the more I believe the problem is somewhere else.

如果 drawRect 方法甚至没有调用?我继续尝试强制它被调用:

What if the drawRect method is not even called? I went on to try to force it being called:

view.contentMode = UIViewContentModeRedraw;
[view setNeedsDisplay];

也不起作用。

所以我的问题是:

如何强制 UIView 调用 drawRect 在这种情况下,甚至是我执行不当的应用?

How to force UIView to call drawRect in this case or even my swizzled implementation?

谢谢!

推荐答案

首先,阅读绘制或不绘制(当何时应该使用drawRect / Core Graphics与子视图/图像,为什么?)

基本上, UIView 检查是否覆盖了 drawRect:。如果您不重写它,则它可以进行许多图形优化,并且甚至不会调用该方法。

Basically, UIView checks if you override drawRect: or not. If you don't override it, it can do lots of drawing optimizations and the method won't be even called.

在这种情况下,您没有重写它,因此 UIView 认为没有理由调用它,即使您用其他东西替换了空的实现。

In this case you didn't override it so UIView sees no reason to call it, even if you replaced the empty implementation with something else.

这篇关于混乱时未调用UIView的drawRect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆