I can't figure out how to make a function, that will give information to the parent object, that has done something, so I need your help. Example what I want to make:
ViewController
class instantiate class BottomView
and adds it as it's subview.BottomView
class to start animate something.ViewController
class, that it could release/remove an instance BottomView
from itself.I need something like a callback. Could you help please?
You could do something like this
@interface BottomView : UIView
@property (nonatomic, copy) void (^onCompletion)(void);
- (void)start;
@end
@implementation BottomView
- (void)start
{
[UIView animateWithDuration:0.25f
animations:^{
// do some animation
} completion:^(BOOL finished){
if (self.onCompletion) {
self.onCompletion();
}
}];
}
@end
Which you would use like
BottomView *bottomView = [[BottomView alloc] initWithFrame:...];
bottomView.onCompletion = ^{
[bottomView removeFromSuperview];
NSLog(@"So something when animation is finished and view is remove");
};
[self.view addSubview:bottomView];
[bottomView start];
1.You can do it with blocks!
You can pass some block to BottomView.
2. Or you can do it with target-action.
you can pass to BottomView selector @selector(myMethod:)
as action,
and pointer to the view controller as target. And after animation ends
use performeSelector:
method.
3. Or you can define delegate @protocol and implement methods in your viewController, and add delegate property in BottomView. @property (assign) id delegate;
If you make some animations in your BottomView, you can use UIView method
animateWithDuration:delay:options:animations:completion:
that uses blocks as callbacks
[UIView animateWithDuration:1.0f animations:^{
}];
update:
in ButtomView.h
@class BottomView;
@protocol BottomViewDelegate <NSObject>
- (void)bottomViewAnimationDone:(BottomView *) bottomView;
@end
@interface BottomView : UIView
@property (nonatomic, assign) id <BottomViewDelegate> delegate;
.....
@end
in ButtomView.m
- (void)notifyDelegateAboutAnimationDone {
if ([self.delegate respondsToSelector:@selector(bottomViewAnimationDone:)]) {
[self.delegate bottomViewAnimationDone:self];
}
}
and after animation complit you should call [self notifyDelegateAboutAnimationDone];
you should set you ViewController class to confirm to protocol BottomViewDelegate
in MyViewController.h
@interface MyViewController : UIViewController <BottomViewDelegate>
...
@end
and f.e. in viewDidLoad
you should set bottomView.delegate = self;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With