call method in a subclass of UIView

为君一笑 提交于 2019-12-10 12:19:04

问题


I've got a UIViewController and an own class, a subclass of UIView.

In my ViewController I make a instance of the uiview. If I tap the uiview a function gets called within it and an overlay appears. TO get rid of that overlay later the user has to tap somewhere on the screen(besides the instance of my class)

How do I tell my class to dismiss the overlay? I already thought of delegate.

So my thoughts were to make a MyUIViewControllerdelegate. If my viewcontroller receives a tap the delegate should be called. THe only problem is how do I tell my subclass that it should receive that delegate? I Have no instance of my viewcontroller in my subclass so I can not set the delegate.

Any Ideas? Hope my problem is clear :)

Thanks a lot


回答1:


The only problem is how do I tell my subclass that it should receive that delegate? I Have no instance of my viewcontroller in my subclass so I can not set the delegate.

MyUIView.h:

@protocol MyUIViewDelegate;

@interface MyUIView : UIView
{
    ...
    id<MyUIViewDelegate> delegate;
    ...
}

...
@property (nonatomic, assign) id<MyUIViewDelegate> delegate;
...

@end

@protocol MyUIViewDelegate <NSObject>
- (void)myUIViewDidFinish:(MyUIView*)myUIView;
@end

MyUIView.m:

...
@synthesize delegate;
...

- (void)dismiss
{
    [delegate myUIViewDidFinish:self];
}

MyUIViewController.h:

#import "MyUIView.h"

@interface MyUIViewController : UIViewController <MyUIViewDelegate>
{
    ...
    MyUIView* myOverlay;
    ...
}

...
@property (nonatomic, retain) IBOutlet MyUIView* myOverlay;
...

@end

MyUIViewController.m:

...
@synthesize myOverlay;
...

- (void)dealloc
{
    ...
    [myOverlay release];
    ...

    [super dealloc];
}

...

- (void)viewDidLoad
{
    [super viewDidLoad];

    ...
    myOverlay.delegate = self;
    ...
}

...

- (void)showMyUIView
{
    // ... show myOverlay ...
}

...

#pragma mark MyUIViewDelegate Methods

- (void)myUIViewDidFinish:(MyUIView*)myUIView
{
    // ... hide myOverlay ...
}


来源:https://stackoverflow.com/questions/2506927/call-method-in-a-subclass-of-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!