【问题标题】:objective c subclass UIImageView目标c子类UIImageView
【发布时间】:2011-07-29 04:30:33
【问题描述】:

我正在尝试继承 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,则不会显示任何内容。 我错过了什么?

【问题讨论】:

  • 你为什么有@synthesize image;?你没有定义属性?您的示例中似乎缺少某些内容。

标签: objective-c xcode inheritance uiimageview subclass


【解决方案1】:

您正在合成image,因此当您尝试使用点符号设置图像时,会阻止对超类(即UIImageView)上的setImage 的调用。

删除这一行:

@synthesize image;

【讨论】:

  • 感谢您的即时回复!这就是造成问题的原因。只是为了说清楚,如果我不想在我的子类中自定义 getter/setter,我不应该使用 @synthesize 吗?
  • @CrisDeBlonde @synthesize 的存在是为了为您创建访问器方法,在自定义 getter 和 setter 时是否使用它取决于您。见Declared Properties
  • 非常感谢您的回答。现在我想我已经更清楚了。
【解决方案2】:

我建议使用 Objective-C“类别”而不是子类化 UIImageView。只要您不必添加任何成员变量,Category 就是更好的解决方案。当您使用类别时,您可以在原始类的任何实例上调用您的扩展函数(在您的情况下为 UIImageView。这消除了您在任何可能想要使用新函数的地方有意识地使用子类的需要。

您可以在标题中执行以下操作:

@interface UIImageView (UIImageView+URL)

-(void) retrieveImageFromUrl: (NSString *)the_URL;

@end

然后在一个实施文件中:

@implimentation UIImageView (UIImageView+URL)    

-(void) retrieveImageFromUrl: (NSString *)the_URL
{
    // implimentation
}

@end

然后你想在 UIImageView 上使用你的新函数,你只需要包含头文件。

【讨论】:

  • 非常感谢您的回复!确实我对类别了解不多,但是在这种情况下,稍后我会添加一些需要的成员变量,以及更多的方法。这只是子类构建的开始。无论如何,再次感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2012-07-27
相关资源
最近更新 更多