Objective C 子类 UIImageView
我正在尝试对 UIImageView 进行子类化以在其中添加一些自定义功能。我开始尝试做基础知识,只需用给定的图像初始化一个对象并将其显示在屏幕上。
使用 UIImageView
一切正常,但如果我将对象从 UIImageView
更改为自定义类,则不会显示图像。
这是我到目前为止所做的:
//Imager.h
#import <UIKit/UIKit.h>
@interface Imager : UIImageView {
}
-(id) init;
-(void) retrieveImageFromUrl: (NSString *)the_URL;
@end
//Imager.m
#import "Imager.h"
@implementation Imager
@synthesize image;
-(id)init
{
self = [super init];
return self;
}
-(void) retrieveImageFromUrl: (NSString *)the_URL{
//Not implemented yet
}
@end
所以,我正在使用这个语句: cell.postImage.image = [UIImage imageNamed:@"img.png"];
在执行此操作之前,我还有 postImage = [[UIImageView alloc] init];
如果 postImage 被声明为 UIImageView 一切都会按预期工作。但如果我将其更改为 Imager,则不会显示任何内容。 我缺少什么?
I'm trying to subclass UIImageView
to add some custom functionality in it. I started trying to do the basics, just init an object with a given image and display it on the screen.
Using UIImageView
everything works fine, but if i change my object from UIImageView
to my custom class, no image is displayed.
Here's what i've done so far:
//Imager.h
#import <UIKit/UIKit.h>
@interface Imager : UIImageView {
}
-(id) init;
-(void) retrieveImageFromUrl: (NSString *)the_URL;
@end
//Imager.m
#import "Imager.h"
@implementation Imager
@synthesize image;
-(id)init
{
self = [super init];
return self;
}
-(void) retrieveImageFromUrl: (NSString *)the_URL{
//Not implemented yet
}
@end
So, i am using this statment: cell.postImage.image = [UIImage imageNamed:@"img.png"];
Before this is executed, i also have postImage = [[UIImageView alloc] init];
If postImage is declared as UIImageView everything works as expected. But if i change it to Imager instead, then nothing is displayed.
What am i missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在合成
image
,因此当您尝试使用点表示法设置图像时,会阻止对超类(即UIImageView
)上的setImage
的调用图像。删除这一行:
You're synthesizing
image
, thus blocking calls tosetImage
on the superclass (i.e.UIImageView
) when you attempt to use the dot notation to set the image.Remove this line:
我建议使用 Objective-C“类别”而不是子类化 UIImageView。只要您不必添加任何成员变量,类别就是更好的解决方案。当您使用类别时,您可以在原始类的任何实例上调用扩展函数(在您的情况下为 UIImageView)。这使您无需在任何可能想要使用新函数的地方有意识地使用子类。
您只需执行以下操作即可:在标题中:
然后在实现文件中:
然后,无论您想在 UIImageView 上使用新函数,您只需要包含头文件即可。
I would suggest using an Objective-C "Category" instead of subclassing the UIImageView. As long as you don't have to add any member variables, a Category is a better solution. When you use a category you can call your extended functions on any instance of the original class (in your case UIImageView. That removes the need for you to consciously use your subclass anywhere you might want to use your new functions.
You can just do the following in a header:
Then in an implimentation file:
Then wherever you want to use your new function on a UIImageView, you just need to include the header file.