开发者

My UIImageView doesn't get all the methods of my subclassed UIImageView

I created a subclass (called MyPicture) of the UIImageView with this methodes:

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"-- I AM TOUCHED --");
}

//…

When I create a UIImageView with the InterfaceBuilder with the class MyPicture everything works and the console writes: "I AM TOUCHED". But only, when I activate User Interaction Enabled in IB.

But when I create the UIImageView programmatly, it doenst work. in the ViewController.h:

MyButton * foo;

In the ViewController.m:

- (void)viewDidLoad {
    flo = [[UIImageView alloc]initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
    foo.userInteract开发者_StackOverflow社区ionEnabled = YES;
    foo.image = [UIImage imageNamed:@"Picture 1.png"];
    [self.view addSubview:foo];
    [super viewDidLoad];
}

I can see the picture, so it has to be my UIImageView subclass. But why doesn't he detect the touches?


I don't see why it has to be your subclass. Seeing the picture just means it's a UIImageView. Which is exactly what it is (not the subclass) Here:

foo = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];

you are initializing a UIImageView, not your sub class. Try changing that line to:

foo = [[MyPicture alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];

Edit: Also, since you set userInteractionEnabled = YES in your subclasses 'initWithFrame:' method, there's no reason you have to do it again in this line:

foo.userInteractionEnabled = YES;


When you subclass UIImageView there are a couple different ways the application can call the object into being. UIImageViews created in Interface Builder are pre-compiled and loaded into memory without calling an -(id)init method. Instead, they call - (void)awakeFromNib after the contents of the nib are loaded into memory.

Make sure your class identity is set to your subclass and set userInteractionEnabled in the awakeFromNib method in your subclass. This will allow you to set user interaction without binding.

To completely load the UIImageView programmatically, make sure your allocating from the right class. Your code was calling from the UIImageView superclass.

- (void)viewDidLoad {
    foo = [[MyImageView alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
    foo.image = [UIImage imageNamed:@"Picture 1.png"];
    [self.view addSubview:foo];
    [super viewDidLoad];
}

This will call the - (id)initWithFrame from your subclass instead of the superclass and perform your custom code. This also sends the - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event calls to your subclass instead of to the superclass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜