drawRect不在我的UIImageView的子类中被调用 [英] drawRect not being called in my subclass of UIImageView

查看:153
本文介绍了drawRect不在我的UIImageView的子类中被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有UIImageView的子类,并试图覆盖drawRect,所以我可以绘制在图像的顶部使用Quartz 2D。我知道这是一个蠢的新手问题,但我没有看到我做错了。这里是界面:

I have subclassed UIImageView and tried to override drawRect so I could draw on top of the image using Quartz 2D. I know this is a dumb newbie question, but I'm not seeing what I did wrong. Here's the interface:

#import <UIKit/UIKit.h>

@interface UIImageViewCustom : UIImageView {

}
- (void)drawRect:(CGRect)rect;
@end

而实现:

#import "UIImageViewCustom.h"

@implementation UIImageViewCustom

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // do stuff
}

- (void)dealloc {
    [super dealloc];
}
@end

我在 drawRect ,它从来没有打过,导致我认为它永远不会被调用。是不是应该在视图第一次加载时调用?

I set a breakpoint on drawRect and it never hits, leading me to think it never gets called at all. Isn't it supposed to be called when the view first loads? Have I incorrectly overridden it?

推荐答案

只有当视图可见且脏时,才会调用它。也许问题是在创建视图的代码中,或者在您的Nib中,如果这是创建它的方式?

It'll only get called if the view is visible, and dirty. Maybe the problem is in the code that creates the view, or in your Nib, if that's how you're creating it?

有时你会看到断点失败如果您尝试调试发布版本,请正确设置。

You'll also sometimes see breakpoints failing to get set properly if you're trying to debug a "Release" build.

我错过了第一次're子类化UIImageView。从文档:

I somehow missed the first time that you're subclassing UIImageView. From the docs:


特殊注意事项

Special Considerations

UIImageView类已优化为
将其图像绘制到显示器。
UIImageView不会在
子类中调用drawRect:。如果你的子类需要
自定义的绘图代码,建议使用
你使用UIView作为基类。

The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: in a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.

所以你有它。鉴于使用[UIImage drawInRect:]或使用CALayer将图像绘制到视图中有多么容易,那么可能没有很好的理由来继承UIImageView。

So there you have it. Given how easy it is to draw an image into your view using [UIImage drawInRect:], or by using CALayer, there's probably no good reason to subclass UIImageView anyway.

这篇关于drawRect不在我的UIImageView的子类中被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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